diff --git a/lib/composer/autoload_classmap.php b/lib/composer/autoload_classmap.php index 522d0d941..8aeea3e25 100644 --- a/lib/composer/autoload_classmap.php +++ b/lib/composer/autoload_classmap.php @@ -8,6 +8,7 @@ $baseDir = dirname($vendorDir); return array( 'AbstractLoginFSMExtension' => $baseDir . '/application/applicationextension.inc.php', 'AbstractPortalUIExtension' => $baseDir . '/application/applicationextension.inc.php', + 'AbstractWeeklyScheduledProcess' => $baseDir . '/core/backgroundprocess.inc.php', 'Action' => $baseDir . '/core/action.class.inc.php', 'ActionChecker' => $baseDir . '/core/userrights.class.inc.php', 'ActionEmail' => $baseDir . '/core/action.class.inc.php', @@ -364,6 +365,7 @@ return array( 'PrintableDataTable' => $baseDir . '/application/datatable.class.inc.php', 'ProcessException' => $baseDir . '/core/backgroundprocess.inc.php', 'ProcessFatalException' => $baseDir . '/core/backgroundprocess.inc.php', + 'ProcessInvalidConfigException' => $baseDir . '/core/backgroundprocess.inc.php', 'Psr\\Cache\\CacheException' => $vendorDir . '/psr/cache/src/CacheException.php', 'Psr\\Cache\\CacheItemInterface' => $vendorDir . '/psr/cache/src/CacheItemInterface.php', 'Psr\\Cache\\CacheItemPoolInterface' => $vendorDir . '/psr/cache/src/CacheItemPoolInterface.php', @@ -621,7 +623,7 @@ return array( 'Symfony\\Bundle\\FrameworkBundle\\Templating\\TemplateNameParser' => $vendorDir . '/symfony/framework-bundle/Templating/TemplateNameParser.php', 'Symfony\\Bundle\\FrameworkBundle\\Templating\\TemplateReference' => $vendorDir . '/symfony/framework-bundle/Templating/TemplateReference.php', 'Symfony\\Bundle\\FrameworkBundle\\Templating\\TimedPhpEngine' => $vendorDir . '/symfony/framework-bundle/Templating/TimedPhpEngine.php', - 'Symfony\\Bundle\\FrameworkBundle\\Test\\KernelShutdownOnTearDownTrait' => $vendorDir . '/symfony/framework-bundle/Test/KernelShutdownOnTearDownTrait.php', + 'Symfony\\Bundle\\FrameworkBundle\\Test\\ForwardCompatTestTrait' => $vendorDir . '/symfony/framework-bundle/Test/ForwardCompatTestTrait.php', 'Symfony\\Bundle\\FrameworkBundle\\Test\\KernelTestCase' => $vendorDir . '/symfony/framework-bundle/Test/KernelTestCase.php', 'Symfony\\Bundle\\FrameworkBundle\\Test\\WebTestCase' => $vendorDir . '/symfony/framework-bundle/Test/WebTestCase.php', 'Symfony\\Bundle\\FrameworkBundle\\Translation\\PhpExtractor' => $vendorDir . '/symfony/framework-bundle/Translation/PhpExtractor.php', @@ -1453,7 +1455,16 @@ return array( 'Symfony\\Polyfill\\Apcu\\Apcu' => $vendorDir . '/symfony/polyfill-apcu/Apcu.php', 'Symfony\\Polyfill\\Ctype\\Ctype' => $vendorDir . '/symfony/polyfill-ctype/Ctype.php', 'Symfony\\Polyfill\\Mbstring\\Mbstring' => $vendorDir . '/symfony/polyfill-mbstring/Mbstring.php', + 'Symfony\\Polyfill\\Php56\\Php56' => $vendorDir . '/symfony/polyfill-php56/Php56.php', 'Symfony\\Polyfill\\Php70\\Php70' => $vendorDir . '/symfony/polyfill-php70/Php70.php', + 'Symfony\\Polyfill\\Util\\Binary' => $vendorDir . '/symfony/polyfill-util/Binary.php', + 'Symfony\\Polyfill\\Util\\BinaryNoFuncOverload' => $vendorDir . '/symfony/polyfill-util/BinaryNoFuncOverload.php', + 'Symfony\\Polyfill\\Util\\BinaryOnFuncOverload' => $vendorDir . '/symfony/polyfill-util/BinaryOnFuncOverload.php', + 'Symfony\\Polyfill\\Util\\TestListener' => $vendorDir . '/symfony/polyfill-util/TestListener.php', + 'Symfony\\Polyfill\\Util\\TestListenerForV5' => $vendorDir . '/symfony/polyfill-util/TestListenerForV5.php', + 'Symfony\\Polyfill\\Util\\TestListenerForV6' => $vendorDir . '/symfony/polyfill-util/TestListenerForV6.php', + 'Symfony\\Polyfill\\Util\\TestListenerForV7' => $vendorDir . '/symfony/polyfill-util/TestListenerForV7.php', + 'Symfony\\Polyfill\\Util\\TestListenerTrait' => $vendorDir . '/symfony/polyfill-util/TestListenerTrait.php', 'System' => $vendorDir . '/pear/pear-core-minimal/src/System.php', 'TCPDF' => $vendorDir . '/combodo/tcpdf/tcpdf.php', 'TCPDF2DBarcode' => $vendorDir . '/combodo/tcpdf/tcpdf_barcodes_2d.php', diff --git a/lib/composer/autoload_files.php b/lib/composer/autoload_files.php index 9d8f6ca2f..c72a22a20 100644 --- a/lib/composer/autoload_files.php +++ b/lib/composer/autoload_files.php @@ -11,6 +11,7 @@ return array( '5255c38a0faeba867671b61dfda6d864' => $vendorDir . '/paragonie/random_compat/lib/random.php', '023d27dca8066ef29e6739335ea73bad' => $vendorDir . '/symfony/polyfill-php70/bootstrap.php', '32dcc8afd4335739640db7d200c1971d' => $vendorDir . '/symfony/polyfill-apcu/bootstrap.php', + 'bd9634f2d41831496de0d3dfe4c94881' => $vendorDir . '/symfony/polyfill-php56/bootstrap.php', '667aeda72477189d0494fecd327c3641' => $vendorDir . '/symfony/var-dumper/Resources/functions/dump.php', '2c102faa651ef8ea5874edb585946bce' => $vendorDir . '/swiftmailer/swiftmailer/lib/swift_required.php', ); diff --git a/lib/composer/autoload_psr4.php b/lib/composer/autoload_psr4.php index 7b20ab310..c0ba02ab5 100644 --- a/lib/composer/autoload_psr4.php +++ b/lib/composer/autoload_psr4.php @@ -7,7 +7,9 @@ $baseDir = dirname($vendorDir); return array( 'Twig\\' => array($vendorDir . '/twig/twig/src'), + 'Symfony\\Polyfill\\Util\\' => array($vendorDir . '/symfony/polyfill-util'), 'Symfony\\Polyfill\\Php70\\' => array($vendorDir . '/symfony/polyfill-php70'), + 'Symfony\\Polyfill\\Php56\\' => array($vendorDir . '/symfony/polyfill-php56'), 'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'), 'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'), 'Symfony\\Polyfill\\Apcu\\' => array($vendorDir . '/symfony/polyfill-apcu'), diff --git a/lib/composer/autoload_static.php b/lib/composer/autoload_static.php index 5475b2b2a..fdf6ba4d9 100644 --- a/lib/composer/autoload_static.php +++ b/lib/composer/autoload_static.php @@ -12,6 +12,7 @@ class ComposerStaticInit0018331147de7601e7552f7da8e3bb8b '5255c38a0faeba867671b61dfda6d864' => __DIR__ . '/..' . '/paragonie/random_compat/lib/random.php', '023d27dca8066ef29e6739335ea73bad' => __DIR__ . '/..' . '/symfony/polyfill-php70/bootstrap.php', '32dcc8afd4335739640db7d200c1971d' => __DIR__ . '/..' . '/symfony/polyfill-apcu/bootstrap.php', + 'bd9634f2d41831496de0d3dfe4c94881' => __DIR__ . '/..' . '/symfony/polyfill-php56/bootstrap.php', '667aeda72477189d0494fecd327c3641' => __DIR__ . '/..' . '/symfony/var-dumper/Resources/functions/dump.php', '2c102faa651ef8ea5874edb585946bce' => __DIR__ . '/..' . '/swiftmailer/swiftmailer/lib/swift_required.php', ); @@ -23,7 +24,9 @@ class ComposerStaticInit0018331147de7601e7552f7da8e3bb8b ), 'S' => array ( + 'Symfony\\Polyfill\\Util\\' => 22, 'Symfony\\Polyfill\\Php70\\' => 23, + 'Symfony\\Polyfill\\Php56\\' => 23, 'Symfony\\Polyfill\\Mbstring\\' => 26, 'Symfony\\Polyfill\\Ctype\\' => 23, 'Symfony\\Polyfill\\Apcu\\' => 22, @@ -65,10 +68,18 @@ class ComposerStaticInit0018331147de7601e7552f7da8e3bb8b array ( 0 => __DIR__ . '/..' . '/twig/twig/src', ), + 'Symfony\\Polyfill\\Util\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-util', + ), 'Symfony\\Polyfill\\Php70\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-php70', ), + 'Symfony\\Polyfill\\Php56\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-php56', + ), 'Symfony\\Polyfill\\Mbstring\\' => array ( 0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring', @@ -229,6 +240,7 @@ class ComposerStaticInit0018331147de7601e7552f7da8e3bb8b public static $classMap = array ( 'AbstractLoginFSMExtension' => __DIR__ . '/../..' . '/application/applicationextension.inc.php', 'AbstractPortalUIExtension' => __DIR__ . '/../..' . '/application/applicationextension.inc.php', + 'AbstractWeeklyScheduledProcess' => __DIR__ . '/../..' . '/core/backgroundprocess.inc.php', 'Action' => __DIR__ . '/../..' . '/core/action.class.inc.php', 'ActionChecker' => __DIR__ . '/../..' . '/core/userrights.class.inc.php', 'ActionEmail' => __DIR__ . '/../..' . '/core/action.class.inc.php', @@ -585,6 +597,7 @@ class ComposerStaticInit0018331147de7601e7552f7da8e3bb8b 'PrintableDataTable' => __DIR__ . '/../..' . '/application/datatable.class.inc.php', 'ProcessException' => __DIR__ . '/../..' . '/core/backgroundprocess.inc.php', 'ProcessFatalException' => __DIR__ . '/../..' . '/core/backgroundprocess.inc.php', + 'ProcessInvalidConfigException' => __DIR__ . '/../..' . '/core/backgroundprocess.inc.php', 'Psr\\Cache\\CacheException' => __DIR__ . '/..' . '/psr/cache/src/CacheException.php', 'Psr\\Cache\\CacheItemInterface' => __DIR__ . '/..' . '/psr/cache/src/CacheItemInterface.php', 'Psr\\Cache\\CacheItemPoolInterface' => __DIR__ . '/..' . '/psr/cache/src/CacheItemPoolInterface.php', @@ -842,7 +855,7 @@ class ComposerStaticInit0018331147de7601e7552f7da8e3bb8b 'Symfony\\Bundle\\FrameworkBundle\\Templating\\TemplateNameParser' => __DIR__ . '/..' . '/symfony/framework-bundle/Templating/TemplateNameParser.php', 'Symfony\\Bundle\\FrameworkBundle\\Templating\\TemplateReference' => __DIR__ . '/..' . '/symfony/framework-bundle/Templating/TemplateReference.php', 'Symfony\\Bundle\\FrameworkBundle\\Templating\\TimedPhpEngine' => __DIR__ . '/..' . '/symfony/framework-bundle/Templating/TimedPhpEngine.php', - 'Symfony\\Bundle\\FrameworkBundle\\Test\\KernelShutdownOnTearDownTrait' => __DIR__ . '/..' . '/symfony/framework-bundle/Test/KernelShutdownOnTearDownTrait.php', + 'Symfony\\Bundle\\FrameworkBundle\\Test\\ForwardCompatTestTrait' => __DIR__ . '/..' . '/symfony/framework-bundle/Test/ForwardCompatTestTrait.php', 'Symfony\\Bundle\\FrameworkBundle\\Test\\KernelTestCase' => __DIR__ . '/..' . '/symfony/framework-bundle/Test/KernelTestCase.php', 'Symfony\\Bundle\\FrameworkBundle\\Test\\WebTestCase' => __DIR__ . '/..' . '/symfony/framework-bundle/Test/WebTestCase.php', 'Symfony\\Bundle\\FrameworkBundle\\Translation\\PhpExtractor' => __DIR__ . '/..' . '/symfony/framework-bundle/Translation/PhpExtractor.php', @@ -1674,7 +1687,16 @@ class ComposerStaticInit0018331147de7601e7552f7da8e3bb8b 'Symfony\\Polyfill\\Apcu\\Apcu' => __DIR__ . '/..' . '/symfony/polyfill-apcu/Apcu.php', 'Symfony\\Polyfill\\Ctype\\Ctype' => __DIR__ . '/..' . '/symfony/polyfill-ctype/Ctype.php', 'Symfony\\Polyfill\\Mbstring\\Mbstring' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/Mbstring.php', + 'Symfony\\Polyfill\\Php56\\Php56' => __DIR__ . '/..' . '/symfony/polyfill-php56/Php56.php', 'Symfony\\Polyfill\\Php70\\Php70' => __DIR__ . '/..' . '/symfony/polyfill-php70/Php70.php', + 'Symfony\\Polyfill\\Util\\Binary' => __DIR__ . '/..' . '/symfony/polyfill-util/Binary.php', + 'Symfony\\Polyfill\\Util\\BinaryNoFuncOverload' => __DIR__ . '/..' . '/symfony/polyfill-util/BinaryNoFuncOverload.php', + 'Symfony\\Polyfill\\Util\\BinaryOnFuncOverload' => __DIR__ . '/..' . '/symfony/polyfill-util/BinaryOnFuncOverload.php', + 'Symfony\\Polyfill\\Util\\TestListener' => __DIR__ . '/..' . '/symfony/polyfill-util/TestListener.php', + 'Symfony\\Polyfill\\Util\\TestListenerForV5' => __DIR__ . '/..' . '/symfony/polyfill-util/TestListenerForV5.php', + 'Symfony\\Polyfill\\Util\\TestListenerForV6' => __DIR__ . '/..' . '/symfony/polyfill-util/TestListenerForV6.php', + 'Symfony\\Polyfill\\Util\\TestListenerForV7' => __DIR__ . '/..' . '/symfony/polyfill-util/TestListenerForV7.php', + 'Symfony\\Polyfill\\Util\\TestListenerTrait' => __DIR__ . '/..' . '/symfony/polyfill-util/TestListenerTrait.php', 'System' => __DIR__ . '/..' . '/pear/pear-core-minimal/src/System.php', 'TCPDF' => __DIR__ . '/..' . '/combodo/tcpdf/tcpdf.php', 'TCPDF2DBarcode' => __DIR__ . '/..' . '/combodo/tcpdf/tcpdf_barcodes_2d.php', diff --git a/lib/composer/installed.json b/lib/composer/installed.json index 0d3606733..fae852604 100644 --- a/lib/composer/installed.json +++ b/lib/composer/installed.json @@ -504,27 +504,27 @@ }, { "name": "psr/log", - "version": "1.1.0", - "version_normalized": "1.1.0.0", + "version": "1.1.2", + "version_normalized": "1.1.2.0", "source": { "type": "git", "url": "https://github.com/php-fig/log.git", - "reference": "6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd" + "reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/php-fig/log/zipball/6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd", - "reference": "6c001f1daafa3a3ac1d8ff69ee4db8e799a654dd", + "url": "https://api.github.com/repos/php-fig/log/zipball/446d54b4cb6bf489fc9d75f55843658e6f25d801", + "reference": "446d54b4cb6bf489fc9d75f55843658e6f25d801", "shasum": "" }, "require": { "php": ">=5.3.0" }, - "time": "2018-11-20T15:27:04+00:00", + "time": "2019-11-01T11:05:21+00:00", "type": "library", "extra": { "branch-alias": { - "dev-master": "1.0.x-dev" + "dev-master": "1.1.x-dev" } }, "installation-source": "dist", @@ -720,17 +720,17 @@ }, { "name": "symfony/cache", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/cache.git", - "reference": "8c6e162f0f7626771edbfa0a0e45b46623bbae1c" + "reference": "8d5db9c0cecf8b6f79fa96583fae652224d897da" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/cache/zipball/8c6e162f0f7626771edbfa0a0e45b46623bbae1c", - "reference": "8c6e162f0f7626771edbfa0a0e45b46623bbae1c", + "url": "https://api.github.com/repos/symfony/cache/zipball/8d5db9c0cecf8b6f79fa96583fae652224d897da", + "reference": "8d5db9c0cecf8b6f79fa96583fae652224d897da", "shasum": "" }, "require": { @@ -753,7 +753,7 @@ "doctrine/dbal": "~2.4", "predis/predis": "~1.0" }, - "time": "2019-06-17T17:26:15+00:00", + "time": "2019-11-12T12:50:33+00:00", "type": "library", "extra": { "branch-alias": { @@ -792,17 +792,17 @@ }, { "name": "symfony/class-loader", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/class-loader.git", - "reference": "4459eef5298dedfb69f771186a580062b8516497" + "reference": "e212b06996819a2bce026a63da03b7182d05a690" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/class-loader/zipball/4459eef5298dedfb69f771186a580062b8516497", - "reference": "4459eef5298dedfb69f771186a580062b8516497", + "url": "https://api.github.com/repos/symfony/class-loader/zipball/e212b06996819a2bce026a63da03b7182d05a690", + "reference": "e212b06996819a2bce026a63da03b7182d05a690", "shasum": "" }, "require": { @@ -815,7 +815,7 @@ "suggest": { "symfony/polyfill-apcu": "For using ApcClassLoader on HHVM" }, - "time": "2019-01-16T09:39:14+00:00", + "time": "2019-08-20T13:31:17+00:00", "type": "library", "extra": { "branch-alias": { @@ -850,17 +850,17 @@ }, { "name": "symfony/config", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/config.git", - "reference": "623fd6be3e5d4112d667003488c8c3ec12b66f62" + "reference": "c3a30587de97263d2813a3c81b74126c58b67a4f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/config/zipball/623fd6be3e5d4112d667003488c8c3ec12b66f62", - "reference": "623fd6be3e5d4112d667003488c8c3ec12b66f62", + "url": "https://api.github.com/repos/symfony/config/zipball/c3a30587de97263d2813a3c81b74126c58b67a4f", + "reference": "c3a30587de97263d2813a3c81b74126c58b67a4f", "shasum": "" }, "require": { @@ -881,7 +881,7 @@ "suggest": { "symfony/yaml": "To use the yaml reference dumper" }, - "time": "2019-07-17T15:23:18+00:00", + "time": "2019-11-08T08:28:59+00:00", "type": "library", "extra": { "branch-alias": { @@ -916,17 +916,17 @@ }, { "name": "symfony/console", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/console.git", - "reference": "12940f20a816c978860fa4925b3f1bbb27e9ac46" + "reference": "17b154f932c5874cdbda6d05796b6490eec9f9f7" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/console/zipball/12940f20a816c978860fa4925b3f1bbb27e9ac46", - "reference": "12940f20a816c978860fa4925b3f1bbb27e9ac46", + "url": "https://api.github.com/repos/symfony/console/zipball/17b154f932c5874cdbda6d05796b6490eec9f9f7", + "reference": "17b154f932c5874cdbda6d05796b6490eec9f9f7", "shasum": "" }, "require": { @@ -955,7 +955,7 @@ "symfony/lock": "", "symfony/process": "" }, - "time": "2019-07-24T14:46:41+00:00", + "time": "2019-11-13T07:12:39+00:00", "type": "library", "extra": { "branch-alias": { @@ -990,23 +990,23 @@ }, { "name": "symfony/css-selector", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/css-selector.git", - "reference": "8ca29297c29b64fb3a1a135e71cb25f67f9fdccf" + "reference": "f819f71ae3ba6f396b4c015bd5895de7d2f1f85f" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/css-selector/zipball/8ca29297c29b64fb3a1a135e71cb25f67f9fdccf", - "reference": "8ca29297c29b64fb3a1a135e71cb25f67f9fdccf", + "url": "https://api.github.com/repos/symfony/css-selector/zipball/f819f71ae3ba6f396b4c015bd5895de7d2f1f85f", + "reference": "f819f71ae3ba6f396b4c015bd5895de7d2f1f85f", "shasum": "" }, "require": { "php": "^5.5.9|>=7.0.8" }, - "time": "2019-01-16T09:39:14+00:00", + "time": "2019-10-01T11:57:37+00:00", "type": "library", "extra": { "branch-alias": { @@ -1045,17 +1045,17 @@ }, { "name": "symfony/debug", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/debug.git", - "reference": "bc977cb2681d75988ab2d53d14c4245c6c04f82f" + "reference": "f72e33fdb1170b326e72c3157f0cd456351dd086" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/debug/zipball/bc977cb2681d75988ab2d53d14c4245c6c04f82f", - "reference": "bc977cb2681d75988ab2d53d14c4245c6c04f82f", + "url": "https://api.github.com/repos/symfony/debug/zipball/f72e33fdb1170b326e72c3157f0cd456351dd086", + "reference": "f72e33fdb1170b326e72c3157f0cd456351dd086", "shasum": "" }, "require": { @@ -1068,7 +1068,7 @@ "require-dev": { "symfony/http-kernel": "~2.8|~3.0|~4.0" }, - "time": "2019-07-23T08:39:19+00:00", + "time": "2019-10-24T15:33:53+00:00", "type": "library", "extra": { "branch-alias": { @@ -1103,17 +1103,17 @@ }, { "name": "symfony/dependency-injection", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/dependency-injection.git", - "reference": "ade939fe83d5ec5fcaa98628dc42d83232c8eb41" + "reference": "0ea4d39ca82409a25a43b61ce828048a90000920" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/ade939fe83d5ec5fcaa98628dc42d83232c8eb41", - "reference": "ade939fe83d5ec5fcaa98628dc42d83232c8eb41", + "url": "https://api.github.com/repos/symfony/dependency-injection/zipball/0ea4d39ca82409a25a43b61ce828048a90000920", + "reference": "0ea4d39ca82409a25a43b61ce828048a90000920", "shasum": "" }, "require": { @@ -1141,7 +1141,7 @@ "symfony/proxy-manager-bridge": "Generate service proxies to lazy load them", "symfony/yaml": "" }, - "time": "2019-07-19T11:52:08+00:00", + "time": "2019-11-08T16:18:30+00:00", "type": "library", "extra": { "branch-alias": { @@ -1176,26 +1176,26 @@ }, { "name": "symfony/dotenv", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/dotenv.git", - "reference": "3f4fdfb551bf36f2017d75cd2e6490fbe67f9d2d" + "reference": "c7e8e471fea74e868ae797970b383dea89ae548a" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/dotenv/zipball/3f4fdfb551bf36f2017d75cd2e6490fbe67f9d2d", - "reference": "3f4fdfb551bf36f2017d75cd2e6490fbe67f9d2d", + "url": "https://api.github.com/repos/symfony/dotenv/zipball/c7e8e471fea74e868ae797970b383dea89ae548a", + "reference": "c7e8e471fea74e868ae797970b383dea89ae548a", "shasum": "" }, "require": { "php": "^5.5.9|>=7.0.8" }, "require-dev": { - "symfony/process": "~3.2|~4.0" + "symfony/process": "^3.4.2|^4.0" }, - "time": "2019-06-23T08:10:04+00:00", + "time": "2019-10-18T10:00:34+00:00", "type": "library", "extra": { "branch-alias": { @@ -1235,17 +1235,17 @@ }, { "name": "symfony/event-dispatcher", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/event-dispatcher.git", - "reference": "f18fdd6cc7006441865e698420cee26bac94741f" + "reference": "f9031c22ec127d4a2450760f81a8677fe8a10177" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/f18fdd6cc7006441865e698420cee26bac94741f", - "reference": "f18fdd6cc7006441865e698420cee26bac94741f", + "url": "https://api.github.com/repos/symfony/event-dispatcher/zipball/f9031c22ec127d4a2450760f81a8677fe8a10177", + "reference": "f9031c22ec127d4a2450760f81a8677fe8a10177", "shasum": "" }, "require": { @@ -1265,7 +1265,7 @@ "symfony/dependency-injection": "", "symfony/http-kernel": "" }, - "time": "2019-06-25T07:45:31+00:00", + "time": "2019-10-24T15:33:53+00:00", "type": "library", "extra": { "branch-alias": { @@ -1300,24 +1300,24 @@ }, { "name": "symfony/filesystem", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/filesystem.git", - "reference": "70adda061ef83bb7def63a17953dc41f203308a7" + "reference": "00e3a6ddd723b8bcfe4f2a1b6f82b98eeeb51516" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/filesystem/zipball/70adda061ef83bb7def63a17953dc41f203308a7", - "reference": "70adda061ef83bb7def63a17953dc41f203308a7", + "url": "https://api.github.com/repos/symfony/filesystem/zipball/00e3a6ddd723b8bcfe4f2a1b6f82b98eeeb51516", + "reference": "00e3a6ddd723b8bcfe4f2a1b6f82b98eeeb51516", "shasum": "" }, "require": { "php": "^5.5.9|>=7.0.8", "symfony/polyfill-ctype": "~1.8" }, - "time": "2019-06-23T09:29:17+00:00", + "time": "2019-08-20T13:31:17+00:00", "type": "library", "extra": { "branch-alias": { @@ -1352,23 +1352,23 @@ }, { "name": "symfony/finder", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/finder.git", - "reference": "1e762fdf73ace6ceb42ba5a6ca280be86082364a" + "reference": "3e915e5ce305f8bc8017597f71f1f4095092ddf8" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/finder/zipball/1e762fdf73ace6ceb42ba5a6ca280be86082364a", - "reference": "1e762fdf73ace6ceb42ba5a6ca280be86082364a", + "url": "https://api.github.com/repos/symfony/finder/zipball/3e915e5ce305f8bc8017597f71f1f4095092ddf8", + "reference": "3e915e5ce305f8bc8017597f71f1f4095092ddf8", "shasum": "" }, "require": { "php": "^5.5.9|>=7.0.8" }, - "time": "2019-06-28T08:02:59+00:00", + "time": "2019-10-30T12:43:22+00:00", "type": "library", "extra": { "branch-alias": { @@ -1403,32 +1403,32 @@ }, { "name": "symfony/framework-bundle", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/framework-bundle.git", - "reference": "0bb32eafe4adeb39faff1902dd9ec54e0ed2a265" + "reference": "3cb98792e8d1fa332c65b28521eeaa6e9bbeea34" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/framework-bundle/zipball/0bb32eafe4adeb39faff1902dd9ec54e0ed2a265", - "reference": "0bb32eafe4adeb39faff1902dd9ec54e0ed2a265", + "url": "https://api.github.com/repos/symfony/framework-bundle/zipball/3cb98792e8d1fa332c65b28521eeaa6e9bbeea34", + "reference": "3cb98792e8d1fa332c65b28521eeaa6e9bbeea34", "shasum": "" }, "require": { "ext-xml": "*", "php": "^5.5.9|>=7.0.8", - "symfony/cache": "~3.4|~4.0", + "symfony/cache": "~3.4.31|^4.3.4", "symfony/class-loader": "~3.2", - "symfony/config": "~3.4|~4.0", + "symfony/config": "^3.4.31|^4.3.4", "symfony/debug": "~2.8|~3.0|~4.0", "symfony/dependency-injection": "^3.4.24|^4.2.5", "symfony/event-dispatcher": "~3.4|~4.0", "symfony/filesystem": "~2.8|~3.0|~4.0", "symfony/finder": "~2.8|~3.0|~4.0", - "symfony/http-foundation": "^3.3.11|~4.0", - "symfony/http-kernel": "~3.4|~4.0", + "symfony/http-foundation": "^3.4.13|~4.3", + "symfony/http-kernel": "^3.4.31|^4.3.4", "symfony/polyfill-mbstring": "~1.0", "symfony/routing": "^3.4.5|^4.0.5" }, @@ -1447,17 +1447,17 @@ "symfony/workflow": "<3.3" }, "require-dev": { - "doctrine/annotations": "~1.0", + "doctrine/annotations": "~1.7", "doctrine/cache": "~1.0", "fig/link-util": "^1.0", "phpdocumentor/reflection-docblock": "^3.0|^4.0", "symfony/asset": "~3.3|~4.0", "symfony/browser-kit": "~2.8|~3.0|~4.0", - "symfony/console": "~3.4|~4.0", + "symfony/console": "~3.4.31|^4.3.4", "symfony/css-selector": "~2.8|~3.0|~4.0", "symfony/dom-crawler": "~2.8|~3.0|~4.0", "symfony/expression-language": "~2.8|~3.0|~4.0", - "symfony/form": "^3.4.22|~4.1.11|^4.2.3", + "symfony/form": "^3.4.31|^4.3.4", "symfony/lock": "~3.4|~4.0", "symfony/polyfill-intl-icu": "~1.0", "symfony/process": "~2.8|~3.0|~4.0", @@ -1485,7 +1485,7 @@ "symfony/web-link": "For using web links, features such as preloading, prefetching or prerendering", "symfony/yaml": "For using the debug:config and lint:yaml commands" }, - "time": "2019-07-24T16:59:53+00:00", + "time": "2019-11-03T19:32:26+00:00", "type": "symfony-bundle", "extra": { "branch-alias": { @@ -1520,17 +1520,17 @@ }, { "name": "symfony/http-foundation", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/http-foundation.git", - "reference": "c450706851050ade2e1f30d012d50bb9173f7f3d" + "reference": "9e4b3ac8fa3348b4811674d23de32d201de225ce" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-foundation/zipball/c450706851050ade2e1f30d012d50bb9173f7f3d", - "reference": "c450706851050ade2e1f30d012d50bb9173f7f3d", + "url": "https://api.github.com/repos/symfony/http-foundation/zipball/9e4b3ac8fa3348b4811674d23de32d201de225ce", + "reference": "9e4b3ac8fa3348b4811674d23de32d201de225ce", "shasum": "" }, "require": { @@ -1541,7 +1541,7 @@ "require-dev": { "symfony/expression-language": "~2.8|~3.0|~4.0" }, - "time": "2019-07-23T06:27:47+00:00", + "time": "2019-11-11T12:53:10+00:00", "type": "library", "extra": { "branch-alias": { @@ -1576,17 +1576,17 @@ }, { "name": "symfony/http-kernel", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/http-kernel.git", - "reference": "83a1b30c5dd02f5c3cd708a432071d0c99474eb3" + "reference": "e1764b3de00ec5636dd03d02fd44bcb1147d70d9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/http-kernel/zipball/83a1b30c5dd02f5c3cd708a432071d0c99474eb3", - "reference": "83a1b30c5dd02f5c3cd708a432071d0c99474eb3", + "url": "https://api.github.com/repos/symfony/http-kernel/zipball/e1764b3de00ec5636dd03d02fd44bcb1147d70d9", + "reference": "e1764b3de00ec5636dd03d02fd44bcb1147d70d9", "shasum": "" }, "require": { @@ -1595,7 +1595,8 @@ "symfony/debug": "^3.3.3|~4.0", "symfony/event-dispatcher": "~2.8|~3.0|~4.0", "symfony/http-foundation": "~3.4.12|~4.0.12|^4.1.1", - "symfony/polyfill-ctype": "~1.8" + "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-php56": "~1.8" }, "conflict": { "symfony/config": "<2.8", @@ -1632,7 +1633,7 @@ "symfony/finder": "", "symfony/var-dumper": "" }, - "time": "2019-07-27T17:14:06+00:00", + "time": "2019-11-13T08:44:50+00:00", "type": "library", "extra": { "branch-alias": { @@ -1844,6 +1845,64 @@ "shim" ] }, + { + "name": "symfony/polyfill-php56", + "version": "v1.12.0", + "version_normalized": "1.12.0.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php56.git", + "reference": "0e3b212e96a51338639d8ce175c046d7729c3403" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php56/zipball/0e3b212e96a51338639d8ce175c046d7729c3403", + "reference": "0e3b212e96a51338639d8ce175c046d7729c3403", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "symfony/polyfill-util": "~1.0" + }, + "time": "2019-08-06T08:03:45+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.12-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Php56\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 5.6+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ] + }, { "name": "symfony/polyfill-php70", "version": "v1.12.0", @@ -1906,18 +1965,72 @@ ] }, { - "name": "symfony/routing", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "name": "symfony/polyfill-util", + "version": "v1.12.0", + "version_normalized": "1.12.0.0", "source": { "type": "git", - "url": "https://github.com/symfony/routing.git", - "reference": "8d804d8a65a26dc9de1aaf2ff3a421e581d050e6" + "url": "https://github.com/symfony/polyfill-util.git", + "reference": "4317de1386717b4c22caed7725350a8887ab205c" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/routing/zipball/8d804d8a65a26dc9de1aaf2ff3a421e581d050e6", - "reference": "8d804d8a65a26dc9de1aaf2ff3a421e581d050e6", + "url": "https://api.github.com/repos/symfony/polyfill-util/zipball/4317de1386717b4c22caed7725350a8887ab205c", + "reference": "4317de1386717b4c22caed7725350a8887ab205c", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "time": "2019-08-06T08:03:45+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.12-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Util\\": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony utilities for portability of PHP codes", + "homepage": "https://symfony.com", + "keywords": [ + "compat", + "compatibility", + "polyfill", + "shim" + ] + }, + { + "name": "symfony/routing", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/routing.git", + "reference": "afc10b9c6b5196e0fecbc3bd373c7b4482e5b6b5" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/routing/zipball/afc10b9c6b5196e0fecbc3bd373c7b4482e5b6b5", + "reference": "afc10b9c6b5196e0fecbc3bd373c7b4482e5b6b5", "shasum": "" }, "require": { @@ -1944,7 +2057,7 @@ "symfony/http-foundation": "For using a Symfony Request object", "symfony/yaml": "For using the YAML loader" }, - "time": "2019-06-26T11:14:13+00:00", + "time": "2019-11-08T17:25:00+00:00", "type": "library", "extra": { "branch-alias": { @@ -1985,23 +2098,23 @@ }, { "name": "symfony/stopwatch", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/stopwatch.git", - "reference": "2a651c2645c10bbedd21170771f122d935e0dd58" + "reference": "efe0af281ad336bc3b10375c88b117499f1d8494" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/stopwatch/zipball/2a651c2645c10bbedd21170771f122d935e0dd58", - "reference": "2a651c2645c10bbedd21170771f122d935e0dd58", + "url": "https://api.github.com/repos/symfony/stopwatch/zipball/efe0af281ad336bc3b10375c88b117499f1d8494", + "reference": "efe0af281ad336bc3b10375c88b117499f1d8494", "shasum": "" }, "require": { "php": "^5.5.9|>=7.0.8" }, - "time": "2019-01-16T09:39:14+00:00", + "time": "2019-11-03T17:17:59+00:00", "type": "library", "extra": { "branch-alias": { @@ -2036,34 +2149,35 @@ }, { "name": "symfony/twig-bridge", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/twig-bridge.git", - "reference": "bf136ba1fbd18126ab65a930ea0daebb0b0fd159" + "reference": "a2fa4d04a4f22c8abf7d12188d89510e2e9bd1c1" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/twig-bridge/zipball/bf136ba1fbd18126ab65a930ea0daebb0b0fd159", - "reference": "bf136ba1fbd18126ab65a930ea0daebb0b0fd159", + "url": "https://api.github.com/repos/symfony/twig-bridge/zipball/a2fa4d04a4f22c8abf7d12188d89510e2e9bd1c1", + "reference": "a2fa4d04a4f22c8abf7d12188d89510e2e9bd1c1", "shasum": "" }, "require": { "php": "^5.5.9|>=7.0.8", - "twig/twig": "^1.40|^2.9" + "twig/twig": "^1.41|^2.10" }, "conflict": { "symfony/console": "<3.4", - "symfony/form": "<3.4.13|>=4.0,<4.0.13|>=4.1,<4.1.2" + "symfony/form": "<3.4.31|>=4.0,<4.3.4" }, "require-dev": { + "fig/link-util": "^1.0", "symfony/asset": "~2.8|~3.0|~4.0", "symfony/console": "~3.4|~4.0", "symfony/dependency-injection": "~2.8|~3.0|~4.0", "symfony/expression-language": "~2.8|~3.0|~4.0", "symfony/finder": "~2.8|~3.0|~4.0", - "symfony/form": "^3.4.23|^4.2.4", + "symfony/form": "^3.4.31|^4.3.4", "symfony/http-foundation": "^3.3.11|~4.0", "symfony/http-kernel": "~3.2|~4.0", "symfony/polyfill-intl-icu": "~1.0", @@ -2093,7 +2207,7 @@ "symfony/web-link": "For using the WebLinkExtension", "symfony/yaml": "For using the YamlExtension" }, - "time": "2019-07-24T19:39:07+00:00", + "time": "2019-10-24T15:33:53+00:00", "type": "symfony-bridge", "extra": { "branch-alias": { @@ -2128,17 +2242,17 @@ }, { "name": "symfony/twig-bundle", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/twig-bundle.git", - "reference": "fae76fd8d8cff50295282d752e9842324bd277e4" + "reference": "d39ed8f5df62aeeeb27a6f3bf7f58a6c02a58ea9" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/twig-bundle/zipball/fae76fd8d8cff50295282d752e9842324bd277e4", - "reference": "fae76fd8d8cff50295282d752e9842324bd277e4", + "url": "https://api.github.com/repos/symfony/twig-bundle/zipball/d39ed8f5df62aeeeb27a6f3bf7f58a6c02a58ea9", + "reference": "d39ed8f5df62aeeeb27a6f3bf7f58a6c02a58ea9", "shasum": "" }, "require": { @@ -2149,14 +2263,14 @@ "symfony/http-kernel": "^3.3|~4.0", "symfony/polyfill-ctype": "~1.8", "symfony/twig-bridge": "^3.4.3|^4.0.3", - "twig/twig": "~1.40|~2.9" + "twig/twig": "~1.41|~2.10" }, "conflict": { "symfony/dependency-injection": "<3.4", "symfony/event-dispatcher": "<3.3.1" }, "require-dev": { - "doctrine/annotations": "~1.0", + "doctrine/annotations": "~1.7", "doctrine/cache": "~1.0", "symfony/asset": "~2.8|~3.0|~4.0", "symfony/dependency-injection": "~3.4.24|^4.2.5", @@ -2170,7 +2284,7 @@ "symfony/web-link": "~3.3|~4.0", "symfony/yaml": "~2.8|~3.0|~4.0" }, - "time": "2019-07-19T08:16:37+00:00", + "time": "2019-10-01T15:13:36+00:00", "type": "symfony-bundle", "extra": { "branch-alias": { @@ -2205,17 +2319,17 @@ }, { "name": "symfony/var-dumper", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/var-dumper.git", - "reference": "b6a45abfe961183a4c26fad98a6112c487e983bf" + "reference": "569e261461600810845a8305ca3f64abd3e712c0" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/var-dumper/zipball/b6a45abfe961183a4c26fad98a6112c487e983bf", - "reference": "b6a45abfe961183a4c26fad98a6112c487e983bf", + "url": "https://api.github.com/repos/symfony/var-dumper/zipball/569e261461600810845a8305ca3f64abd3e712c0", + "reference": "569e261461600810845a8305ca3f64abd3e712c0", "shasum": "" }, "require": { @@ -2234,7 +2348,7 @@ "ext-intl": "To show region name in time zone dump", "ext-symfony_debug": "" }, - "time": "2019-07-26T11:29:23+00:00", + "time": "2019-10-10T11:03:19+00:00", "type": "library", "extra": { "branch-alias": { @@ -2276,17 +2390,17 @@ }, { "name": "symfony/web-profiler-bundle", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/web-profiler-bundle.git", - "reference": "0e9627b1a3864949fa1d72eec78dab02830b5206" + "reference": "b4c78b585d60a0b96ed735ce40f964bd3a228f73" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/web-profiler-bundle/zipball/0e9627b1a3864949fa1d72eec78dab02830b5206", - "reference": "0e9627b1a3864949fa1d72eec78dab02830b5206", + "url": "https://api.github.com/repos/symfony/web-profiler-bundle/zipball/b4c78b585d60a0b96ed735ce40f964bd3a228f73", + "reference": "b4c78b585d60a0b96ed735ce40f964bd3a228f73", "shasum": "" }, "require": { @@ -2310,7 +2424,7 @@ "symfony/dependency-injection": "~3.4|~4.0", "symfony/stopwatch": "~2.8|~3.0|~4.0" }, - "time": "2019-07-24T10:33:03+00:00", + "time": "2019-10-01T15:13:36+00:00", "type": "symfony-bundle", "extra": { "branch-alias": { @@ -2345,17 +2459,17 @@ }, { "name": "symfony/yaml", - "version": "v3.4.30", - "version_normalized": "3.4.30.0", + "version": "v3.4.35", + "version_normalized": "3.4.35.0", "source": { "type": "git", "url": "https://github.com/symfony/yaml.git", - "reference": "051d045c684148060ebfc9affb7e3f5e0899d40b" + "reference": "dab657db15207879217fc81df4f875947bf68804" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/symfony/yaml/zipball/051d045c684148060ebfc9affb7e3f5e0899d40b", - "reference": "051d045c684148060ebfc9affb7e3f5e0899d40b", + "url": "https://api.github.com/repos/symfony/yaml/zipball/dab657db15207879217fc81df4f875947bf68804", + "reference": "dab657db15207879217fc81df4f875947bf68804", "shasum": "" }, "require": { @@ -2371,7 +2485,7 @@ "suggest": { "symfony/console": "For validating YAML files using the lint command" }, - "time": "2019-07-24T13:01:31+00:00", + "time": "2019-10-24T15:33:53+00:00", "type": "library", "extra": { "branch-alias": { @@ -2406,29 +2520,29 @@ }, { "name": "twig/twig", - "version": "v1.42.2", - "version_normalized": "1.42.2.0", + "version": "v1.42.4", + "version_normalized": "1.42.4.0", "source": { "type": "git", "url": "https://github.com/twigphp/Twig.git", - "reference": "21707d6ebd05476854805e4f91b836531941bcd4" + "reference": "e587180584c3d2d6cb864a0454e777bb6dcb6152" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/twigphp/Twig/zipball/21707d6ebd05476854805e4f91b836531941bcd4", - "reference": "21707d6ebd05476854805e4f91b836531941bcd4", + "url": "https://api.github.com/repos/twigphp/Twig/zipball/e587180584c3d2d6cb864a0454e777bb6dcb6152", + "reference": "e587180584c3d2d6cb864a0454e777bb6dcb6152", "shasum": "" }, "require": { - "php": ">=5.4.0", + "php": ">=5.5.0", "symfony/polyfill-ctype": "^1.8" }, "require-dev": { "psr/container": "^1.0", - "symfony/debug": "^2.7", - "symfony/phpunit-bridge": "^3.4.19|^4.1.8|^5.0" + "symfony/debug": "^3.4|^4.2", + "symfony/phpunit-bridge": "^4.4@dev|^5.0" }, - "time": "2019-06-18T15:35:16+00:00", + "time": "2019-11-11T16:49:32+00:00", "type": "library", "extra": { "branch-alias": { @@ -2451,19 +2565,19 @@ "authors": [ { "name": "Fabien Potencier", - "role": "Lead Developer", "email": "fabien@symfony.com", - "homepage": "http://fabien.potencier.org" - }, - { - "name": "Armin Ronacher", - "role": "Project Founder", - "email": "armin.ronacher@active-4.com" + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" }, { "name": "Twig Team", - "role": "Contributors", - "homepage": "https://twig.symfony.com/contributors" + "homepage": "https://twig.symfony.com/contributors", + "role": "Contributors" + }, + { + "name": "Armin Ronacher", + "email": "armin.ronacher@active-4.com", + "role": "Project Founder" } ], "description": "Twig, the flexible, fast, and secure template language for PHP", diff --git a/lib/psr/log/Psr/Log/LoggerInterface.php b/lib/psr/log/Psr/Log/LoggerInterface.php index 5ea72438b..e695046e3 100644 --- a/lib/psr/log/Psr/Log/LoggerInterface.php +++ b/lib/psr/log/Psr/Log/LoggerInterface.php @@ -118,6 +118,8 @@ interface LoggerInterface * @param array $context * * @return void + * + * @throws \Psr\Log\InvalidArgumentException */ public function log($level, $message, array $context = array()); } diff --git a/lib/psr/log/Psr/Log/LoggerTrait.php b/lib/psr/log/Psr/Log/LoggerTrait.php index 867225df1..e392fef0a 100644 --- a/lib/psr/log/Psr/Log/LoggerTrait.php +++ b/lib/psr/log/Psr/Log/LoggerTrait.php @@ -135,6 +135,8 @@ trait LoggerTrait * @param array $context * * @return void + * + * @throws \Psr\Log\InvalidArgumentException */ abstract public function log($level, $message, array $context = array()); } diff --git a/lib/psr/log/Psr/Log/NullLogger.php b/lib/psr/log/Psr/Log/NullLogger.php index d8cd682c8..c8f7293b1 100644 --- a/lib/psr/log/Psr/Log/NullLogger.php +++ b/lib/psr/log/Psr/Log/NullLogger.php @@ -20,6 +20,8 @@ class NullLogger extends AbstractLogger * @param array $context * * @return void + * + * @throws \Psr\Log\InvalidArgumentException */ public function log($level, $message, array $context = array()) { diff --git a/lib/psr/log/Psr/Log/Test/LoggerInterfaceTest.php b/lib/psr/log/Psr/Log/Test/LoggerInterfaceTest.php index 4b861c3ef..9ecb6c4b0 100644 --- a/lib/psr/log/Psr/Log/Test/LoggerInterfaceTest.php +++ b/lib/psr/log/Psr/Log/Test/LoggerInterfaceTest.php @@ -4,6 +4,7 @@ namespace Psr\Log\Test; use Psr\Log\LoggerInterface; use Psr\Log\LogLevel; +use PHPUnit\Framework\TestCase; /** * Provides a base test class for ensuring compliance with the LoggerInterface. @@ -11,7 +12,7 @@ use Psr\Log\LogLevel; * Implementors can extend the class and implement abstract methods to run this * as part of their test suite. */ -abstract class LoggerInterfaceTest extends \PHPUnit_Framework_TestCase +abstract class LoggerInterfaceTest extends TestCase { /** * @return LoggerInterface @@ -140,5 +141,6 @@ class DummyTest { public function __toString() { + return 'DummyTest'; } } diff --git a/lib/psr/log/Psr/Log/Test/TestLogger.php b/lib/psr/log/Psr/Log/Test/TestLogger.php index 0cdffe4f9..1be323049 100644 --- a/lib/psr/log/Psr/Log/Test/TestLogger.php +++ b/lib/psr/log/Psr/Log/Test/TestLogger.php @@ -142,5 +142,6 @@ class TestLogger extends AbstractLogger public function reset() { $this->records = []; + $this->recordsByLevel = []; } } diff --git a/lib/psr/log/README.md b/lib/psr/log/README.md index 5571a25e8..a9f20c437 100644 --- a/lib/psr/log/README.md +++ b/lib/psr/log/README.md @@ -38,6 +38,12 @@ class Foo if ($this->logger) { $this->logger->info('Doing work'); } + + try { + $this->doSomethingElse(); + } catch (Exception $exception) { + $this->logger->error('Oh no!', array('exception' => $exception)); + } // do something useful } diff --git a/lib/psr/log/composer.json b/lib/psr/log/composer.json index 87934d707..3f6d4eea4 100644 --- a/lib/psr/log/composer.json +++ b/lib/psr/log/composer.json @@ -20,7 +20,7 @@ }, "extra": { "branch-alias": { - "dev-master": "1.0.x-dev" + "dev-master": "1.1.x-dev" } } } diff --git a/lib/symfony/cache/Adapter/AbstractAdapter.php b/lib/symfony/cache/Adapter/AbstractAdapter.php index 0868c16d4..62e102e99 100644 --- a/lib/symfony/cache/Adapter/AbstractAdapter.php +++ b/lib/symfony/cache/Adapter/AbstractAdapter.php @@ -49,7 +49,7 @@ abstract class AbstractAdapter implements AdapterInterface, LoggerAwareInterface throw new InvalidArgumentException(sprintf('Namespace must be %d chars max, %d given ("%s")', $this->maxIdLength - 24, \strlen($namespace), $namespace)); } $this->createCacheItem = \Closure::bind( - function ($key, $value, $isHit) use ($defaultLifetime) { + static function ($key, $value, $isHit) use ($defaultLifetime) { $item = new CacheItem(); $item->key = $key; $item->value = $value; @@ -63,7 +63,7 @@ abstract class AbstractAdapter implements AdapterInterface, LoggerAwareInterface ); $getId = function ($key) { return $this->getId((string) $key); }; $this->mergeByLifetime = \Closure::bind( - function ($deferred, $namespace, &$expiredIds) use ($getId) { + static function ($deferred, $namespace, &$expiredIds) use ($getId) { $byLifetime = []; $now = time(); $expiredIds = []; @@ -86,11 +86,10 @@ abstract class AbstractAdapter implements AdapterInterface, LoggerAwareInterface } /** - * @param string $namespace - * @param int $defaultLifetime - * @param string $version - * @param string $directory - * @param LoggerInterface|null $logger + * @param string $namespace + * @param int $defaultLifetime + * @param string $version + * @param string $directory * * @return AdapterInterface */ @@ -276,6 +275,16 @@ abstract class AbstractAdapter implements AdapterInterface, LoggerAwareInterface return $ok; } + public function __sleep() + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup() + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + public function __destruct() { if ($this->deferred) { diff --git a/lib/symfony/cache/Adapter/ArrayAdapter.php b/lib/symfony/cache/Adapter/ArrayAdapter.php index 858a47e9a..4c6695e26 100644 --- a/lib/symfony/cache/Adapter/ArrayAdapter.php +++ b/lib/symfony/cache/Adapter/ArrayAdapter.php @@ -34,7 +34,7 @@ class ArrayAdapter implements AdapterInterface, LoggerAwareInterface, Resettable { $this->storeSerialized = $storeSerialized; $this->createCacheItem = \Closure::bind( - function ($key, $value, $isHit) use ($defaultLifetime) { + static function ($key, $value, $isHit) use ($defaultLifetime) { $item = new CacheItem(); $item->key = $key; $item->value = $value; diff --git a/lib/symfony/cache/Adapter/ChainAdapter.php b/lib/symfony/cache/Adapter/ChainAdapter.php index 1f4d319e4..0080db711 100644 --- a/lib/symfony/cache/Adapter/ChainAdapter.php +++ b/lib/symfony/cache/Adapter/ChainAdapter.php @@ -56,7 +56,7 @@ class ChainAdapter implements AdapterInterface, PruneableInterface, ResettableIn $this->adapterCount = \count($this->adapters); $this->syncItem = \Closure::bind( - function ($sourceItem, $item) use ($defaultLifetime) { + static function ($sourceItem, $item) use ($defaultLifetime) { $item->value = $sourceItem->value; $item->expiry = $sourceItem->expiry; $item->isHit = $sourceItem->isHit; diff --git a/lib/symfony/cache/Adapter/DoctrineAdapter.php b/lib/symfony/cache/Adapter/DoctrineAdapter.php index 972d2b415..8081d7dc3 100644 --- a/lib/symfony/cache/Adapter/DoctrineAdapter.php +++ b/lib/symfony/cache/Adapter/DoctrineAdapter.php @@ -19,9 +19,8 @@ class DoctrineAdapter extends AbstractAdapter use DoctrineTrait; /** - * @param CacheProvider $provider - * @param string $namespace - * @param int $defaultLifetime + * @param string $namespace + * @param int $defaultLifetime */ public function __construct(CacheProvider $provider, $namespace = '', $defaultLifetime = 0) { diff --git a/lib/symfony/cache/Adapter/PhpArrayAdapter.php b/lib/symfony/cache/Adapter/PhpArrayAdapter.php index 42a414209..76673e0a0 100644 --- a/lib/symfony/cache/Adapter/PhpArrayAdapter.php +++ b/lib/symfony/cache/Adapter/PhpArrayAdapter.php @@ -42,7 +42,7 @@ class PhpArrayAdapter implements AdapterInterface, PruneableInterface, Resettabl $this->pool = $fallbackPool; $this->zendDetectUnicode = filter_var(ini_get('zend.detect_unicode'), FILTER_VALIDATE_BOOLEAN); $this->createCacheItem = \Closure::bind( - function ($key, $value, $isHit) { + static function ($key, $value, $isHit) { $item = new CacheItem(); $item->key = $key; $item->value = $value; @@ -266,7 +266,7 @@ class PhpArrayAdapter implements AdapterInterface, PruneableInterface, Resettabl /** * @throws \ReflectionException When $class is not found and is required * - * @internal + * @internal to be removed in Symfony 5.0 */ public static function throwOnRequiredClass($class) { diff --git a/lib/symfony/cache/Adapter/ProxyAdapter.php b/lib/symfony/cache/Adapter/ProxyAdapter.php index 0b7918287..f57482684 100644 --- a/lib/symfony/cache/Adapter/ProxyAdapter.php +++ b/lib/symfony/cache/Adapter/ProxyAdapter.php @@ -31,9 +31,8 @@ class ProxyAdapter implements AdapterInterface, PruneableInterface, ResettableIn private $poolHash; /** - * @param CacheItemPoolInterface $pool - * @param string $namespace - * @param int $defaultLifetime + * @param string $namespace + * @param int $defaultLifetime */ public function __construct(CacheItemPoolInterface $pool, $namespace = '', $defaultLifetime = 0) { @@ -42,7 +41,7 @@ class ProxyAdapter implements AdapterInterface, PruneableInterface, ResettableIn $this->namespace = '' === $namespace ? '' : CacheItem::validateKey($namespace); $this->namespaceLen = \strlen($namespace); $this->createCacheItem = \Closure::bind( - function ($key, $innerItem) use ($defaultLifetime, $poolHash) { + static function ($key, $innerItem) use ($defaultLifetime, $poolHash) { $item = new CacheItem(); $item->key = $key; $item->defaultLifetime = $defaultLifetime; diff --git a/lib/symfony/cache/Adapter/TagAwareAdapter.php b/lib/symfony/cache/Adapter/TagAwareAdapter.php index 362aceed0..ecdd0d699 100644 --- a/lib/symfony/cache/Adapter/TagAwareAdapter.php +++ b/lib/symfony/cache/Adapter/TagAwareAdapter.php @@ -42,7 +42,7 @@ class TagAwareAdapter implements TagAwareAdapterInterface, PruneableInterface, R $this->tags = $tagsPool ?: $itemsPool; $this->knownTagVersionsTtl = $knownTagVersionsTtl; $this->createCacheItem = \Closure::bind( - function ($key, $value, CacheItem $protoItem) { + static function ($key, $value, CacheItem $protoItem) { $item = new CacheItem(); $item->key = $key; $item->value = $value; @@ -56,7 +56,7 @@ class TagAwareAdapter implements TagAwareAdapterInterface, PruneableInterface, R CacheItem::class ); $this->setCacheItemTags = \Closure::bind( - function (CacheItem $item, $key, array &$itemTags) { + static function (CacheItem $item, $key, array &$itemTags) { if (!$item->isHit) { return $item; } @@ -76,7 +76,7 @@ class TagAwareAdapter implements TagAwareAdapterInterface, PruneableInterface, R CacheItem::class ); $this->getTagsByKey = \Closure::bind( - function ($deferred) { + static function ($deferred) { $tagsByKey = []; foreach ($deferred as $key => $item) { $tagsByKey[$key] = $item->tags; @@ -88,7 +88,7 @@ class TagAwareAdapter implements TagAwareAdapterInterface, PruneableInterface, R CacheItem::class ); $this->invalidateTags = \Closure::bind( - function (AdapterInterface $tagsAdapter, array $tags) { + static function (AdapterInterface $tagsAdapter, array $tags) { foreach ($tags as $v) { $v->defaultLifetime = 0; $v->expiry = null; @@ -156,7 +156,14 @@ class TagAwareAdapter implements TagAwareAdapterInterface, PruneableInterface, R if (!$this->pool->hasItem($key)) { return false; } - if (!$itemTags = $this->pool->getItem(static::TAGS_PREFIX.$key)->get()) { + + $itemTags = $this->pool->getItem(static::TAGS_PREFIX.$key); + + if (!$itemTags->isHit()) { + return false; + } + + if (!$itemTags = $itemTags->get()) { return true; } @@ -177,6 +184,8 @@ class TagAwareAdapter implements TagAwareAdapterInterface, PruneableInterface, R foreach ($this->getItems([$key]) as $item) { return $item; } + + return null; } /** @@ -273,6 +282,16 @@ class TagAwareAdapter implements TagAwareAdapterInterface, PruneableInterface, R return $this->invalidateTags([]); } + public function __sleep() + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup() + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + public function __destruct() { $this->commit(); @@ -294,7 +313,10 @@ class TagAwareAdapter implements TagAwareAdapterInterface, PruneableInterface, R } unset($tagKeys[$key]); - $itemTags[$key] = $item->get() ?: []; + + if ($item->isHit()) { + $itemTags[$key] = $item->get() ?: []; + } if (!$tagKeys) { $tagVersions = $this->getTagVersions($itemTags); @@ -348,7 +370,7 @@ class TagAwareAdapter implements TagAwareAdapterInterface, PruneableInterface, R continue; } $version -= $this->knownTagVersions[$tag][1]; - if ((0 !== $version && 1 !== $version) || $this->knownTagVersionsTtl > $now - $this->knownTagVersions[$tag][0]) { + if ((0 !== $version && 1 !== $version) || $now - $this->knownTagVersions[$tag][0] >= $this->knownTagVersionsTtl) { // reuse previously fetched tag versions up to the ttl, unless we are storing items or a potential miss arises $fetchTagVersions = true; } else { diff --git a/lib/symfony/cache/CacheItem.php b/lib/symfony/cache/CacheItem.php index 4ab5d1a26..d7edb7f80 100644 --- a/lib/symfony/cache/CacheItem.php +++ b/lib/symfony/cache/CacheItem.php @@ -56,6 +56,8 @@ final class CacheItem implements CacheItemInterface /** * {@inheritdoc} + * + * @return $this */ public function set($value) { @@ -66,6 +68,8 @@ final class CacheItem implements CacheItemInterface /** * {@inheritdoc} + * + * @return $this */ public function expiresAt($expiration) { @@ -82,6 +86,8 @@ final class CacheItem implements CacheItemInterface /** * {@inheritdoc} + * + * @return $this */ public function expiresAfter($time) { @@ -103,7 +109,7 @@ final class CacheItem implements CacheItemInterface * * @param string|string[] $tags A tag or array of tags * - * @return static + * @return $this * * @throws InvalidArgumentException When $tag is not valid */ diff --git a/lib/symfony/cache/DataCollector/CacheDataCollector.php b/lib/symfony/cache/DataCollector/CacheDataCollector.php index a2f826d70..c9e87d5cc 100644 --- a/lib/symfony/cache/DataCollector/CacheDataCollector.php +++ b/lib/symfony/cache/DataCollector/CacheDataCollector.php @@ -30,8 +30,7 @@ class CacheDataCollector extends DataCollector implements LateDataCollectorInter private $instances = []; /** - * @param string $name - * @param TraceableAdapter $instance + * @param string $name */ public function addInstance($name, TraceableAdapter $instance) { diff --git a/lib/symfony/cache/DoctrineProvider.php b/lib/symfony/cache/DoctrineProvider.php index cebe95fbc..4c5cd0cb1 100644 --- a/lib/symfony/cache/DoctrineProvider.php +++ b/lib/symfony/cache/DoctrineProvider.php @@ -90,7 +90,7 @@ class DoctrineProvider extends CacheProvider implements PruneableInterface, Rese */ protected function doFlush() { - $this->pool->clear(); + return $this->pool->clear(); } /** @@ -98,5 +98,6 @@ class DoctrineProvider extends CacheProvider implements PruneableInterface, Rese */ protected function doGetStats() { + return null; } } diff --git a/lib/symfony/cache/Simple/DoctrineCache.php b/lib/symfony/cache/Simple/DoctrineCache.php index 00f0b9c6f..ea1a4eda5 100644 --- a/lib/symfony/cache/Simple/DoctrineCache.php +++ b/lib/symfony/cache/Simple/DoctrineCache.php @@ -19,9 +19,8 @@ class DoctrineCache extends AbstractCache use DoctrineTrait; /** - * @param CacheProvider $provider - * @param string $namespace - * @param int $defaultLifetime + * @param string $namespace + * @param int $defaultLifetime */ public function __construct(CacheProvider $provider, $namespace = '', $defaultLifetime = 0) { diff --git a/lib/symfony/cache/Simple/MemcachedCache.php b/lib/symfony/cache/Simple/MemcachedCache.php index 771774062..94a9f297d 100644 --- a/lib/symfony/cache/Simple/MemcachedCache.php +++ b/lib/symfony/cache/Simple/MemcachedCache.php @@ -20,9 +20,8 @@ class MemcachedCache extends AbstractCache protected $maxIdLength = 250; /** - * @param \Memcached $client - * @param string $namespace - * @param int $defaultLifetime + * @param string $namespace + * @param int $defaultLifetime */ public function __construct(\Memcached $client, $namespace = '', $defaultLifetime = 0) { diff --git a/lib/symfony/cache/Simple/Psr6Cache.php b/lib/symfony/cache/Simple/Psr6Cache.php index 85d75becb..aab41f722 100644 --- a/lib/symfony/cache/Simple/Psr6Cache.php +++ b/lib/symfony/cache/Simple/Psr6Cache.php @@ -41,7 +41,7 @@ class Psr6Cache implements CacheInterface, PruneableInterface, ResettableInterfa } $cacheItemPrototype = &$this->cacheItemPrototype; $createCacheItem = \Closure::bind( - function ($key, $value, $allowInt = false) use (&$cacheItemPrototype) { + static function ($key, $value, $allowInt = false) use (&$cacheItemPrototype) { $item = clone $cacheItemPrototype; $item->key = $allowInt && \is_int($key) ? (string) $key : CacheItem::validateKey($key); $item->value = $value; diff --git a/lib/symfony/cache/Tests/Adapter/AbstractRedisAdapterTest.php b/lib/symfony/cache/Tests/Adapter/AbstractRedisAdapterTest.php index 5fcec9a26..d1fa9535c 100644 --- a/lib/symfony/cache/Tests/Adapter/AbstractRedisAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/AbstractRedisAdapterTest.php @@ -28,7 +28,7 @@ abstract class AbstractRedisAdapterTest extends AdapterTestCase return new RedisAdapter(self::$redis, str_replace('\\', '.', __CLASS__), $defaultLifetime); } - public static function setupBeforeClass() + public static function setUpBeforeClass() { if (!\extension_loaded('redis')) { self::markTestSkipped('Extension redis required.'); diff --git a/lib/symfony/cache/Tests/Adapter/ChainAdapterTest.php b/lib/symfony/cache/Tests/Adapter/ChainAdapterTest.php index 3b42697fe..5e48930dd 100644 --- a/lib/symfony/cache/Tests/Adapter/ChainAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/ChainAdapterTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Cache\Tests\Adapter; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Cache\Adapter\AdapterInterface; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\Adapter\ChainAdapter; @@ -29,21 +30,17 @@ class ChainAdapterTest extends AdapterTestCase return new ChainAdapter([new ArrayAdapter($defaultLifetime), new ExternalAdapter(), new FilesystemAdapter('', $defaultLifetime)], $defaultLifetime); } - /** - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage At least one adapter must be specified. - */ public function testEmptyAdaptersException() { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('At least one adapter must be specified.'); new ChainAdapter([]); } - /** - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage The class "stdClass" does not implement - */ public function testInvalidAdapterException() { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The class "stdClass" does not implement'); new ChainAdapter([new \stdClass()]); } @@ -69,7 +66,7 @@ class ChainAdapterTest extends AdapterTestCase } /** - * @return \PHPUnit_Framework_MockObject_MockObject|PruneableCacheInterface + * @return MockObject|PruneableCacheInterface */ private function getPruneableMock() { @@ -86,7 +83,7 @@ class ChainAdapterTest extends AdapterTestCase } /** - * @return \PHPUnit_Framework_MockObject_MockObject|PruneableCacheInterface + * @return MockObject|PruneableCacheInterface */ private function getFailingPruneableMock() { @@ -103,7 +100,7 @@ class ChainAdapterTest extends AdapterTestCase } /** - * @return \PHPUnit_Framework_MockObject_MockObject|AdapterInterface + * @return MockObject|AdapterInterface */ private function getNonPruneableMock() { diff --git a/lib/symfony/cache/Tests/Adapter/MaxIdLengthAdapterTest.php b/lib/symfony/cache/Tests/Adapter/MaxIdLengthAdapterTest.php index 8bea26810..536e2c2d4 100644 --- a/lib/symfony/cache/Tests/Adapter/MaxIdLengthAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/MaxIdLengthAdapterTest.php @@ -40,6 +40,10 @@ class MaxIdLengthAdapterTest extends TestCase ->setConstructorArgs([str_repeat('-', 26)]) ->getMock(); + $cache + ->method('doFetch') + ->willReturn(['2:']); + $reflectionClass = new \ReflectionClass(AbstractAdapter::class); $reflectionMethod = $reflectionClass->getMethod('getId'); @@ -56,19 +60,17 @@ class MaxIdLengthAdapterTest extends TestCase $reflectionProperty->setValue($cache, true); // Versioning enabled - $this->assertEquals('--------------------------:1:------------', $reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)])); + $this->assertEquals('--------------------------:2:------------', $reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)])); $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 12)]))); $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 23)]))); $this->assertLessThanOrEqual(50, \strlen($reflectionMethod->invokeArgs($cache, [str_repeat('-', 40)]))); } - /** - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Namespace must be 26 chars max, 40 given ("----------------------------------------") - */ public function testTooLongNamespace() { - $cache = $this->getMockBuilder(MaxIdLengthAdapter::class) + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Namespace must be 26 chars max, 40 given ("----------------------------------------")'); + $this->getMockBuilder(MaxIdLengthAdapter::class) ->setConstructorArgs([str_repeat('-', 40)]) ->getMock(); } diff --git a/lib/symfony/cache/Tests/Adapter/MemcachedAdapterTest.php b/lib/symfony/cache/Tests/Adapter/MemcachedAdapterTest.php index 2a88fea18..3a996079a 100644 --- a/lib/symfony/cache/Tests/Adapter/MemcachedAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/MemcachedAdapterTest.php @@ -23,7 +23,7 @@ class MemcachedAdapterTest extends AdapterTestCase protected static $client; - public static function setupBeforeClass() + public static function setUpBeforeClass() { if (!MemcachedAdapter::isSupported()) { self::markTestSkipped('Extension memcached >=2.2.0 required.'); @@ -63,11 +63,11 @@ class MemcachedAdapterTest extends AdapterTestCase /** * @dataProvider provideBadOptions - * @expectedException \ErrorException - * @expectedExceptionMessage constant(): Couldn't find constant Memcached:: */ public function testBadOptions($name, $value) { + $this->expectException('ErrorException'); + $this->expectExceptionMessage('constant(): Couldn\'t find constant Memcached::'); MemcachedAdapter::createConnection([], [$name => $value]); } @@ -93,12 +93,10 @@ class MemcachedAdapterTest extends AdapterTestCase $this->assertSame(1, $client->getOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE)); } - /** - * @expectedException \Symfony\Component\Cache\Exception\CacheException - * @expectedExceptionMessage MemcachedAdapter: "serializer" option must be "php" or "igbinary". - */ public function testOptionSerializer() { + $this->expectException('Symfony\Component\Cache\Exception\CacheException'); + $this->expectExceptionMessage('MemcachedAdapter: "serializer" option must be "php" or "igbinary".'); if (!\Memcached::HAVE_JSON) { $this->markTestSkipped('Memcached::HAVE_JSON required'); } diff --git a/lib/symfony/cache/Tests/Adapter/PdoAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PdoAdapterTest.php index b587cf6d6..dd2a91185 100644 --- a/lib/symfony/cache/Tests/Adapter/PdoAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/PdoAdapterTest.php @@ -23,7 +23,7 @@ class PdoAdapterTest extends AdapterTestCase protected static $dbFile; - public static function setupBeforeClass() + public static function setUpBeforeClass() { if (!\extension_loaded('pdo_sqlite')) { self::markTestSkipped('Extension pdo_sqlite required.'); diff --git a/lib/symfony/cache/Tests/Adapter/PdoDbalAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PdoDbalAdapterTest.php index d0699f1e3..aa53958cf 100644 --- a/lib/symfony/cache/Tests/Adapter/PdoDbalAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/PdoDbalAdapterTest.php @@ -24,7 +24,7 @@ class PdoDbalAdapterTest extends AdapterTestCase protected static $dbFile; - public static function setupBeforeClass() + public static function setUpBeforeClass() { if (!\extension_loaded('pdo_sqlite')) { self::markTestSkipped('Extension pdo_sqlite required.'); diff --git a/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterTest.php index a227adffa..751f758cc 100644 --- a/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterTest.php @@ -55,7 +55,7 @@ class PhpArrayAdapterTest extends AdapterTestCase protected static $file; - public static function setupBeforeClass() + public static function setUpBeforeClass() { self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php'; } diff --git a/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterWithFallbackTest.php b/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterWithFallbackTest.php index a7feced4e..4bdd7580f 100644 --- a/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterWithFallbackTest.php +++ b/lib/symfony/cache/Tests/Adapter/PhpArrayAdapterWithFallbackTest.php @@ -30,7 +30,7 @@ class PhpArrayAdapterWithFallbackTest extends AdapterTestCase protected static $file; - public static function setupBeforeClass() + public static function setUpBeforeClass() { self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php'; } diff --git a/lib/symfony/cache/Tests/Adapter/PredisAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PredisAdapterTest.php index f311a3539..6aadbf266 100644 --- a/lib/symfony/cache/Tests/Adapter/PredisAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/PredisAdapterTest.php @@ -16,9 +16,9 @@ use Symfony\Component\Cache\Adapter\RedisAdapter; class PredisAdapterTest extends AbstractRedisAdapterTest { - public static function setupBeforeClass() + public static function setUpBeforeClass() { - parent::setupBeforeClass(); + parent::setUpBeforeClass(); self::$redis = new \Predis\Client(['host' => getenv('REDIS_HOST')]); } diff --git a/lib/symfony/cache/Tests/Adapter/PredisClusterAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PredisClusterAdapterTest.php index f723dc446..1afabaf1d 100644 --- a/lib/symfony/cache/Tests/Adapter/PredisClusterAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/PredisClusterAdapterTest.php @@ -13,9 +13,9 @@ namespace Symfony\Component\Cache\Tests\Adapter; class PredisClusterAdapterTest extends AbstractRedisAdapterTest { - public static function setupBeforeClass() + public static function setUpBeforeClass() { - parent::setupBeforeClass(); + parent::setUpBeforeClass(); self::$redis = new \Predis\Client([['host' => getenv('REDIS_HOST')]]); } diff --git a/lib/symfony/cache/Tests/Adapter/PredisRedisClusterAdapterTest.php b/lib/symfony/cache/Tests/Adapter/PredisRedisClusterAdapterTest.php index 6bf0348a1..5b09919e2 100644 --- a/lib/symfony/cache/Tests/Adapter/PredisRedisClusterAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/PredisRedisClusterAdapterTest.php @@ -13,7 +13,7 @@ namespace Symfony\Component\Cache\Tests\Adapter; class PredisRedisClusterAdapterTest extends AbstractRedisAdapterTest { - public static function setupBeforeClass() + public static function setUpBeforeClass() { if (!$hosts = getenv('REDIS_CLUSTER_HOSTS')) { self::markTestSkipped('REDIS_CLUSTER_HOSTS env var is not defined.'); diff --git a/lib/symfony/cache/Tests/Adapter/ProxyAdapterTest.php b/lib/symfony/cache/Tests/Adapter/ProxyAdapterTest.php index f69ad6793..810cb31a2 100644 --- a/lib/symfony/cache/Tests/Adapter/ProxyAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/ProxyAdapterTest.php @@ -32,12 +32,10 @@ class ProxyAdapterTest extends AdapterTestCase return new ProxyAdapter(new ArrayAdapter(), '', $defaultLifetime); } - /** - * @expectedException \Exception - * @expectedExceptionMessage OK bar - */ public function testProxyfiedItem() { + $this->expectException('Exception'); + $this->expectExceptionMessage('OK bar'); $item = new CacheItem(); $pool = new ProxyAdapter(new TestingArrayAdapter($item)); diff --git a/lib/symfony/cache/Tests/Adapter/RedisAdapterTest.php b/lib/symfony/cache/Tests/Adapter/RedisAdapterTest.php index eb2cbd46f..edc6a9934 100644 --- a/lib/symfony/cache/Tests/Adapter/RedisAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/RedisAdapterTest.php @@ -17,9 +17,9 @@ use Symfony\Component\Cache\Traits\RedisProxy; class RedisAdapterTest extends AbstractRedisAdapterTest { - public static function setupBeforeClass() + public static function setUpBeforeClass() { - parent::setupBeforeClass(); + parent::setUpBeforeClass(); self::$redis = AbstractAdapter::createConnection('redis://'.getenv('REDIS_HOST'), ['lazy' => true]); } @@ -55,11 +55,11 @@ class RedisAdapterTest extends AbstractRedisAdapterTest /** * @dataProvider provideFailedCreateConnection - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Redis connection failed */ public function testFailedCreateConnection($dsn) { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Redis connection failed'); RedisAdapter::createConnection($dsn); } @@ -74,11 +74,11 @@ class RedisAdapterTest extends AbstractRedisAdapterTest /** * @dataProvider provideInvalidCreateConnection - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid Redis DSN */ public function testInvalidCreateConnection($dsn) { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid Redis DSN'); RedisAdapter::createConnection($dsn); } diff --git a/lib/symfony/cache/Tests/Adapter/RedisArrayAdapterTest.php b/lib/symfony/cache/Tests/Adapter/RedisArrayAdapterTest.php index 749b039a0..bd9def326 100644 --- a/lib/symfony/cache/Tests/Adapter/RedisArrayAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/RedisArrayAdapterTest.php @@ -13,7 +13,7 @@ namespace Symfony\Component\Cache\Tests\Adapter; class RedisArrayAdapterTest extends AbstractRedisAdapterTest { - public static function setupBeforeClass() + public static function setUpBeforeClass() { parent::setupBeforeClass(); if (!class_exists('RedisArray')) { diff --git a/lib/symfony/cache/Tests/Adapter/RedisClusterAdapterTest.php b/lib/symfony/cache/Tests/Adapter/RedisClusterAdapterTest.php index 852079c00..9c339d2dd 100644 --- a/lib/symfony/cache/Tests/Adapter/RedisClusterAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/RedisClusterAdapterTest.php @@ -13,7 +13,7 @@ namespace Symfony\Component\Cache\Tests\Adapter; class RedisClusterAdapterTest extends AbstractRedisAdapterTest { - public static function setupBeforeClass() + public static function setUpBeforeClass() { if (!class_exists('RedisCluster')) { self::markTestSkipped('The RedisCluster class is required.'); diff --git a/lib/symfony/cache/Tests/Adapter/TagAwareAdapterTest.php b/lib/symfony/cache/Tests/Adapter/TagAwareAdapterTest.php index 488127cc9..0108b9250 100644 --- a/lib/symfony/cache/Tests/Adapter/TagAwareAdapterTest.php +++ b/lib/symfony/cache/Tests/Adapter/TagAwareAdapterTest.php @@ -11,6 +11,8 @@ namespace Symfony\Component\Cache\Tests\Adapter; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Cache\CacheItemInterface; use Symfony\Component\Cache\Adapter\AdapterInterface; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\Cache\Adapter\TagAwareAdapter; @@ -30,11 +32,9 @@ class TagAwareAdapterTest extends AdapterTestCase FilesystemAdapterTest::rmdir(sys_get_temp_dir().'/symfony-cache'); } - /** - * @expectedException \Psr\Cache\InvalidArgumentException - */ public function testInvalidTag() { + $this->expectException('Psr\Cache\InvalidArgumentException'); $pool = $this->createCachePool(); $item = $pool->getItem('foo'); $item->tag(':'); @@ -161,8 +161,119 @@ class TagAwareAdapterTest extends AdapterTestCase $this->assertFalse($cache->prune()); } + public function testKnownTagVersionsTtl() + { + $itemsPool = new FilesystemAdapter('', 10); + $tagsPool = $this + ->getMockBuilder(AdapterInterface::class) + ->getMock(); + + $pool = new TagAwareAdapter($itemsPool, $tagsPool, 10); + + $item = $pool->getItem('foo'); + $item->tag(['baz']); + $item->expiresAfter(100); + + $tag = $this->getMockBuilder(CacheItemInterface::class)->getMock(); + $tag->expects(self::exactly(2))->method('get')->willReturn(10); + + $tagsPool->expects(self::exactly(2))->method('getItems')->willReturn([ + 'baz'.TagAwareAdapter::TAGS_PREFIX => $tag, + ]); + + $pool->save($item); + $this->assertTrue($pool->getItem('foo')->isHit()); + $this->assertTrue($pool->getItem('foo')->isHit()); + + sleep(20); + + $this->assertTrue($pool->getItem('foo')->isHit()); + + sleep(5); + + $this->assertTrue($pool->getItem('foo')->isHit()); + } + + public function testTagEntryIsCreatedForItemWithoutTags() + { + $pool = $this->createCachePool(); + + $itemKey = 'foo'; + $item = $pool->getItem($itemKey); + $pool->save($item); + + $adapter = new FilesystemAdapter(); + $this->assertTrue($adapter->hasItem(TagAwareAdapter::TAGS_PREFIX.$itemKey)); + } + + public function testHasItemReturnsFalseWhenPoolDoesNotHaveItemTags() + { + $pool = $this->createCachePool(); + + $itemKey = 'foo'; + $item = $pool->getItem($itemKey); + $pool->save($item); + + $anotherPool = $this->createCachePool(); + + $adapter = new FilesystemAdapter(); + $adapter->deleteItem(TagAwareAdapter::TAGS_PREFIX.$itemKey); //simulate item losing tags pair + + $this->assertFalse($anotherPool->hasItem($itemKey)); + } + + public function testGetItemReturnsCacheMissWhenPoolDoesNotHaveItemTags() + { + $pool = $this->createCachePool(); + + $itemKey = 'foo'; + $item = $pool->getItem($itemKey); + $pool->save($item); + + $anotherPool = $this->createCachePool(); + + $adapter = new FilesystemAdapter(); + $adapter->deleteItem(TagAwareAdapter::TAGS_PREFIX.$itemKey); //simulate item losing tags pair + + $item = $anotherPool->getItem($itemKey); + $this->assertFalse($item->isHit()); + } + + public function testHasItemReturnsFalseWhenPoolDoesNotHaveItemAndOnlyHasTags() + { + $pool = $this->createCachePool(); + + $itemKey = 'foo'; + $item = $pool->getItem($itemKey); + $pool->save($item); + + $anotherPool = $this->createCachePool(); + + $adapter = new FilesystemAdapter(); + $adapter->deleteItem($itemKey); //simulate losing item but keeping tags + + $this->assertFalse($anotherPool->hasItem($itemKey)); + } + + public function testGetItemReturnsCacheMissWhenPoolDoesNotHaveItemAndOnlyHasTags() + { + $pool = $this->createCachePool(); + + $itemKey = 'foo'; + $item = $pool->getItem($itemKey); + $pool->save($item); + + $anotherPool = $this->createCachePool(); + + $adapter = new FilesystemAdapter(); + $adapter->deleteItem($itemKey); //simulate losing item but keeping tags + + $item = $anotherPool->getItem($itemKey); + $this->assertFalse($item->isHit()); + } + /** - * @return \PHPUnit_Framework_MockObject_MockObject|PruneableCacheInterface + * @return MockObject|PruneableCacheInterface */ private function getPruneableMock() { @@ -179,7 +290,7 @@ class TagAwareAdapterTest extends AdapterTestCase } /** - * @return \PHPUnit_Framework_MockObject_MockObject|PruneableCacheInterface + * @return MockObject|PruneableCacheInterface */ private function getFailingPruneableMock() { @@ -196,7 +307,7 @@ class TagAwareAdapterTest extends AdapterTestCase } /** - * @return \PHPUnit_Framework_MockObject_MockObject|AdapterInterface + * @return MockObject|AdapterInterface */ private function getNonPruneableMock() { diff --git a/lib/symfony/cache/Tests/CacheItemTest.php b/lib/symfony/cache/Tests/CacheItemTest.php index fff5202b1..28c681d15 100644 --- a/lib/symfony/cache/Tests/CacheItemTest.php +++ b/lib/symfony/cache/Tests/CacheItemTest.php @@ -23,11 +23,11 @@ class CacheItemTest extends TestCase /** * @dataProvider provideInvalidKey - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Cache key */ public function testInvalidKey($key) { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Cache key'); CacheItem::validateKey($key); } @@ -66,11 +66,11 @@ class CacheItemTest extends TestCase /** * @dataProvider provideInvalidKey - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Cache tag */ public function testInvalidTag($tag) { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Cache tag'); $item = new CacheItem(); $item->tag($tag); } diff --git a/lib/symfony/cache/Tests/Simple/AbstractRedisCacheTest.php b/lib/symfony/cache/Tests/Simple/AbstractRedisCacheTest.php index dd5e1509c..e6d10284e 100644 --- a/lib/symfony/cache/Tests/Simple/AbstractRedisCacheTest.php +++ b/lib/symfony/cache/Tests/Simple/AbstractRedisCacheTest.php @@ -28,7 +28,7 @@ abstract class AbstractRedisCacheTest extends CacheTestCase return new RedisCache(self::$redis, str_replace('\\', '.', __CLASS__), $defaultLifetime); } - public static function setupBeforeClass() + public static function setUpBeforeClass() { if (!\extension_loaded('redis')) { self::markTestSkipped('Extension redis required.'); diff --git a/lib/symfony/cache/Tests/Simple/ChainCacheTest.php b/lib/symfony/cache/Tests/Simple/ChainCacheTest.php index aa7788791..f216bc1f3 100644 --- a/lib/symfony/cache/Tests/Simple/ChainCacheTest.php +++ b/lib/symfony/cache/Tests/Simple/ChainCacheTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\Cache\Tests\Simple; +use PHPUnit\Framework\MockObject\MockObject; use Psr\SimpleCache\CacheInterface; use Symfony\Component\Cache\PruneableInterface; use Symfony\Component\Cache\Simple\ArrayCache; @@ -27,21 +28,17 @@ class ChainCacheTest extends CacheTestCase return new ChainCache([new ArrayCache($defaultLifetime), new FilesystemCache('', $defaultLifetime)], $defaultLifetime); } - /** - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage At least one cache must be specified. - */ public function testEmptyCachesException() { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('At least one cache must be specified.'); new ChainCache([]); } - /** - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage The class "stdClass" does not implement - */ public function testInvalidCacheException() { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The class "stdClass" does not implement'); new ChainCache([new \stdClass()]); } @@ -67,7 +64,7 @@ class ChainCacheTest extends CacheTestCase } /** - * @return \PHPUnit_Framework_MockObject_MockObject|PruneableCacheInterface + * @return MockObject|PruneableCacheInterface */ private function getPruneableMock() { @@ -84,7 +81,7 @@ class ChainCacheTest extends CacheTestCase } /** - * @return \PHPUnit_Framework_MockObject_MockObject|PruneableCacheInterface + * @return MockObject|PruneableCacheInterface */ private function getFailingPruneableMock() { @@ -101,7 +98,7 @@ class ChainCacheTest extends CacheTestCase } /** - * @return \PHPUnit_Framework_MockObject_MockObject|CacheInterface + * @return MockObject|CacheInterface */ private function getNonPruneableMock() { diff --git a/lib/symfony/cache/Tests/Simple/MemcachedCacheTest.php b/lib/symfony/cache/Tests/Simple/MemcachedCacheTest.php index f83f0a2e3..21332232b 100644 --- a/lib/symfony/cache/Tests/Simple/MemcachedCacheTest.php +++ b/lib/symfony/cache/Tests/Simple/MemcachedCacheTest.php @@ -24,7 +24,7 @@ class MemcachedCacheTest extends CacheTestCase protected static $client; - public static function setupBeforeClass() + public static function setUpBeforeClass() { if (!MemcachedCache::isSupported()) { self::markTestSkipped('Extension memcached >=2.2.0 required.'); @@ -73,11 +73,11 @@ class MemcachedCacheTest extends CacheTestCase /** * @dataProvider provideBadOptions - * @expectedException \ErrorException - * @expectedExceptionMessage constant(): Couldn't find constant Memcached:: */ public function testBadOptions($name, $value) { + $this->expectException('ErrorException'); + $this->expectExceptionMessage('constant(): Couldn\'t find constant Memcached::'); MemcachedCache::createConnection([], [$name => $value]); } @@ -102,12 +102,10 @@ class MemcachedCacheTest extends CacheTestCase $this->assertSame(1, $client->getOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE)); } - /** - * @expectedException \Symfony\Component\Cache\Exception\CacheException - * @expectedExceptionMessage MemcachedAdapter: "serializer" option must be "php" or "igbinary". - */ public function testOptionSerializer() { + $this->expectException('Symfony\Component\Cache\Exception\CacheException'); + $this->expectExceptionMessage('MemcachedAdapter: "serializer" option must be "php" or "igbinary".'); if (!\Memcached::HAVE_JSON) { $this->markTestSkipped('Memcached::HAVE_JSON required'); } diff --git a/lib/symfony/cache/Tests/Simple/PdoCacheTest.php b/lib/symfony/cache/Tests/Simple/PdoCacheTest.php index 665db09f6..f5a26341f 100644 --- a/lib/symfony/cache/Tests/Simple/PdoCacheTest.php +++ b/lib/symfony/cache/Tests/Simple/PdoCacheTest.php @@ -23,7 +23,7 @@ class PdoCacheTest extends CacheTestCase protected static $dbFile; - public static function setupBeforeClass() + public static function setUpBeforeClass() { if (!\extension_loaded('pdo_sqlite')) { self::markTestSkipped('Extension pdo_sqlite required.'); diff --git a/lib/symfony/cache/Tests/Simple/PdoDbalCacheTest.php b/lib/symfony/cache/Tests/Simple/PdoDbalCacheTest.php index ce1a9ae4f..4da2b603c 100644 --- a/lib/symfony/cache/Tests/Simple/PdoDbalCacheTest.php +++ b/lib/symfony/cache/Tests/Simple/PdoDbalCacheTest.php @@ -24,7 +24,7 @@ class PdoDbalCacheTest extends CacheTestCase protected static $dbFile; - public static function setupBeforeClass() + public static function setUpBeforeClass() { if (!\extension_loaded('pdo_sqlite')) { self::markTestSkipped('Extension pdo_sqlite required.'); diff --git a/lib/symfony/cache/Tests/Simple/PhpArrayCacheTest.php b/lib/symfony/cache/Tests/Simple/PhpArrayCacheTest.php index a1bab079c..c18f71442 100644 --- a/lib/symfony/cache/Tests/Simple/PhpArrayCacheTest.php +++ b/lib/symfony/cache/Tests/Simple/PhpArrayCacheTest.php @@ -49,7 +49,7 @@ class PhpArrayCacheTest extends CacheTestCase protected static $file; - public static function setupBeforeClass() + public static function setUpBeforeClass() { self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php'; } diff --git a/lib/symfony/cache/Tests/Simple/PhpArrayCacheWithFallbackTest.php b/lib/symfony/cache/Tests/Simple/PhpArrayCacheWithFallbackTest.php index abee5e787..eba749cec 100644 --- a/lib/symfony/cache/Tests/Simple/PhpArrayCacheWithFallbackTest.php +++ b/lib/symfony/cache/Tests/Simple/PhpArrayCacheWithFallbackTest.php @@ -36,7 +36,7 @@ class PhpArrayCacheWithFallbackTest extends CacheTestCase protected static $file; - public static function setupBeforeClass() + public static function setUpBeforeClass() { self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php'; } diff --git a/lib/symfony/cache/Tests/Simple/RedisArrayCacheTest.php b/lib/symfony/cache/Tests/Simple/RedisArrayCacheTest.php index bda39d990..ec5e4c06e 100644 --- a/lib/symfony/cache/Tests/Simple/RedisArrayCacheTest.php +++ b/lib/symfony/cache/Tests/Simple/RedisArrayCacheTest.php @@ -13,7 +13,7 @@ namespace Symfony\Component\Cache\Tests\Simple; class RedisArrayCacheTest extends AbstractRedisCacheTest { - public static function setupBeforeClass() + public static function setUpBeforeClass() { parent::setupBeforeClass(); if (!class_exists('RedisArray')) { diff --git a/lib/symfony/cache/Tests/Simple/RedisCacheTest.php b/lib/symfony/cache/Tests/Simple/RedisCacheTest.php index 407d916c7..c2cd31a5b 100644 --- a/lib/symfony/cache/Tests/Simple/RedisCacheTest.php +++ b/lib/symfony/cache/Tests/Simple/RedisCacheTest.php @@ -15,7 +15,7 @@ use Symfony\Component\Cache\Simple\RedisCache; class RedisCacheTest extends AbstractRedisCacheTest { - public static function setupBeforeClass() + public static function setUpBeforeClass() { parent::setupBeforeClass(); self::$redis = RedisCache::createConnection('redis://'.getenv('REDIS_HOST')); @@ -45,11 +45,11 @@ class RedisCacheTest extends AbstractRedisCacheTest /** * @dataProvider provideFailedCreateConnection - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Redis connection failed */ public function testFailedCreateConnection($dsn) { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Redis connection failed'); RedisCache::createConnection($dsn); } @@ -64,11 +64,11 @@ class RedisCacheTest extends AbstractRedisCacheTest /** * @dataProvider provideInvalidCreateConnection - * @expectedException \Symfony\Component\Cache\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid Redis DSN */ public function testInvalidCreateConnection($dsn) { + $this->expectException('Symfony\Component\Cache\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid Redis DSN'); RedisCache::createConnection($dsn); } diff --git a/lib/symfony/cache/Tests/Simple/RedisClusterCacheTest.php b/lib/symfony/cache/Tests/Simple/RedisClusterCacheTest.php index 99d4e518f..6b7f8039d 100644 --- a/lib/symfony/cache/Tests/Simple/RedisClusterCacheTest.php +++ b/lib/symfony/cache/Tests/Simple/RedisClusterCacheTest.php @@ -13,7 +13,7 @@ namespace Symfony\Component\Cache\Tests\Simple; class RedisClusterCacheTest extends AbstractRedisCacheTest { - public static function setupBeforeClass() + public static function setUpBeforeClass() { if (!class_exists('RedisCluster')) { self::markTestSkipped('The RedisCluster class is required.'); diff --git a/lib/symfony/cache/Traits/MemcachedTrait.php b/lib/symfony/cache/Traits/MemcachedTrait.php index 9b7a84ab5..28046e475 100644 --- a/lib/symfony/cache/Traits/MemcachedTrait.php +++ b/lib/symfony/cache/Traits/MemcachedTrait.php @@ -26,7 +26,7 @@ trait MemcachedTrait 'persistent_id' => null, 'username' => null, 'password' => null, - 'serializer' => 'php', + \Memcached::OPT_SERIALIZER => \Memcached::SERIALIZER_PHP, ]; private $client; @@ -249,6 +249,7 @@ trait MemcachedTrait foreach ($this->checkResultCode($this->getClient()->deleteMulti($encodedIds)) as $result) { if (\Memcached::RES_SUCCESS !== $result && \Memcached::RES_NOTFOUND !== $result) { $ok = false; + break; } } diff --git a/lib/symfony/class-loader/ApcClassLoader.php b/lib/symfony/class-loader/ApcClassLoader.php index 83038d749..57d22bfa3 100644 --- a/lib/symfony/class-loader/ApcClassLoader.php +++ b/lib/symfony/class-loader/ApcClassLoader.php @@ -113,6 +113,8 @@ class ApcClassLoader return true; } + + return null; } /** diff --git a/lib/symfony/class-loader/ClassLoader.php b/lib/symfony/class-loader/ClassLoader.php index d727278ee..277aa523d 100644 --- a/lib/symfony/class-loader/ClassLoader.php +++ b/lib/symfony/class-loader/ClassLoader.php @@ -161,6 +161,8 @@ class ClassLoader return true; } + + return null; } /** @@ -203,5 +205,7 @@ class ClassLoader if ($this->useIncludePath && $file = stream_resolve_include_path($classPath)) { return $file; } + + return null; } } diff --git a/lib/symfony/class-loader/MapClassLoader.php b/lib/symfony/class-loader/MapClassLoader.php index a9719d6bd..e6b89e514 100644 --- a/lib/symfony/class-loader/MapClassLoader.php +++ b/lib/symfony/class-loader/MapClassLoader.php @@ -63,8 +63,6 @@ class MapClassLoader */ public function findFile($class) { - if (isset($this->map[$class])) { - return $this->map[$class]; - } + return isset($this->map[$class]) ? $this->map[$class] : null; } } diff --git a/lib/symfony/class-loader/Psr4ClassLoader.php b/lib/symfony/class-loader/Psr4ClassLoader.php index 7ea521d82..f4e79cab6 100644 --- a/lib/symfony/class-loader/Psr4ClassLoader.php +++ b/lib/symfony/class-loader/Psr4ClassLoader.php @@ -55,6 +55,8 @@ class Psr4ClassLoader } } } + + return null; } /** diff --git a/lib/symfony/class-loader/Tests/ClassCollectionLoaderTest.php b/lib/symfony/class-loader/Tests/ClassCollectionLoaderTest.php index 816f3c394..e1d5f56de 100644 --- a/lib/symfony/class-loader/Tests/ClassCollectionLoaderTest.php +++ b/lib/symfony/class-loader/Tests/ClassCollectionLoaderTest.php @@ -208,11 +208,9 @@ class ClassCollectionLoaderTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - */ public function testUnableToLoadClassException() { + $this->expectException('InvalidArgumentException'); if (is_file($file = sys_get_temp_dir().'/foo.php')) { unlink($file); } diff --git a/lib/symfony/class-loader/WinCacheClassLoader.php b/lib/symfony/class-loader/WinCacheClassLoader.php index a7149ce9d..374608bb8 100644 --- a/lib/symfony/class-loader/WinCacheClassLoader.php +++ b/lib/symfony/class-loader/WinCacheClassLoader.php @@ -112,6 +112,8 @@ class WinCacheClassLoader return true; } + + return null; } /** diff --git a/lib/symfony/class-loader/XcacheClassLoader.php b/lib/symfony/class-loader/XcacheClassLoader.php index 56965df4c..d236bb4f0 100644 --- a/lib/symfony/class-loader/XcacheClassLoader.php +++ b/lib/symfony/class-loader/XcacheClassLoader.php @@ -106,6 +106,8 @@ class XcacheClassLoader return true; } + + return null; } /** diff --git a/lib/symfony/config/Definition/ArrayNode.php b/lib/symfony/config/Definition/ArrayNode.php index 2afa629cd..91160ae00 100644 --- a/lib/symfony/config/Definition/ArrayNode.php +++ b/lib/symfony/config/Definition/ArrayNode.php @@ -38,17 +38,13 @@ class ArrayNode extends BaseNode implements PrototypeNodeInterface } /** - * Normalizes keys between the different configuration formats. + * {@inheritdoc} * * Namely, you mostly have foo_bar in YAML while you have foo-bar in XML. * After running this method, all keys are normalized to foo_bar. * * If you have a mixed key like foo-bar_moo, it will not be altered. * The key will also not be altered if the target key already exists. - * - * @param mixed $value - * - * @return array The value with normalized keys */ protected function preNormalize($value) { diff --git a/lib/symfony/config/Definition/BaseNode.php b/lib/symfony/config/Definition/BaseNode.php index 905406d12..2b10bffa7 100644 --- a/lib/symfony/config/Definition/BaseNode.php +++ b/lib/symfony/config/Definition/BaseNode.php @@ -49,21 +49,37 @@ abstract class BaseNode implements NodeInterface $this->parent = $parent; } + /** + * @param string $key + */ public function setAttribute($key, $value) { $this->attributes[$key] = $value; } + /** + * @param string $key + * + * @return mixed + */ public function getAttribute($key, $default = null) { return isset($this->attributes[$key]) ? $this->attributes[$key] : $default; } + /** + * @param string $key + * + * @return bool + */ public function hasAttribute($key) { return isset($this->attributes[$key]); } + /** + * @return array + */ public function getAttributes() { return $this->attributes; @@ -74,6 +90,9 @@ abstract class BaseNode implements NodeInterface $this->attributes = $attributes; } + /** + * @param string $key + */ public function removeAttribute($key) { unset($this->attributes[$key]); @@ -92,7 +111,7 @@ abstract class BaseNode implements NodeInterface /** * Returns info message. * - * @return string The info text + * @return string|null The info text */ public function getInfo() { @@ -112,7 +131,7 @@ abstract class BaseNode implements NodeInterface /** * Retrieves the example configuration for this node. * - * @return string|array The example + * @return string|array|null The example */ public function getExample() { @@ -280,9 +299,9 @@ abstract class BaseNode implements NodeInterface /** * Normalizes the value before any other normalization is applied. * - * @param $value + * @param mixed $value * - * @return The normalized array value + * @return mixed The normalized array value */ protected function preNormalize($value) { diff --git a/lib/symfony/config/Definition/Dumper/XmlReferenceDumper.php b/lib/symfony/config/Definition/Dumper/XmlReferenceDumper.php index da05530ac..744f15fd8 100644 --- a/lib/symfony/config/Definition/Dumper/XmlReferenceDumper.php +++ b/lib/symfony/config/Definition/Dumper/XmlReferenceDumper.php @@ -42,10 +42,9 @@ class XmlReferenceDumper } /** - * @param NodeInterface $node - * @param int $depth - * @param bool $root If the node is the root node - * @param string $namespace The namespace of the node + * @param int $depth + * @param bool $root If the node is the root node + * @param string $namespace The namespace of the node */ private function writeNode(NodeInterface $node, $depth = 0, $root = false, $namespace = null) { @@ -307,5 +306,7 @@ class XmlReferenceDumper if (\is_array($value)) { return implode(',', $value); } + + return ''; } } diff --git a/lib/symfony/config/Definition/Dumper/YamlReferenceDumper.php b/lib/symfony/config/Definition/Dumper/YamlReferenceDumper.php index 7aa97909f..5b216d897 100644 --- a/lib/symfony/config/Definition/Dumper/YamlReferenceDumper.php +++ b/lib/symfony/config/Definition/Dumper/YamlReferenceDumper.php @@ -70,10 +70,8 @@ class YamlReferenceDumper } /** - * @param NodeInterface $node - * @param NodeInterface|null $parentNode - * @param int $depth - * @param bool $prototypedArray + * @param int $depth + * @param bool $prototypedArray */ private function writeNode(NodeInterface $node, NodeInterface $parentNode = null, $depth = 0, $prototypedArray = false) { @@ -215,8 +213,6 @@ class YamlReferenceDumper } /** - * @param PrototypedArrayNode $node - * * @return array */ private function getPrototypeChildren(PrototypedArrayNode $node) diff --git a/lib/symfony/config/Definition/PrototypedArrayNode.php b/lib/symfony/config/Definition/PrototypedArrayNode.php index 9a14449c4..7b64d842a 100644 --- a/lib/symfony/config/Definition/PrototypedArrayNode.php +++ b/lib/symfony/config/Definition/PrototypedArrayNode.php @@ -78,7 +78,7 @@ class PrototypedArrayNode extends ArrayNode /** * Retrieves the name of the attribute which value should be used as key. * - * @return string The name of the attribute + * @return string|null The name of the attribute */ public function getKeyAttribute() { diff --git a/lib/symfony/config/Loader/FileLoader.php b/lib/symfony/config/Loader/FileLoader.php index abaf1767d..5ad53885c 100644 --- a/lib/symfony/config/Loader/FileLoader.php +++ b/lib/symfony/config/Loader/FileLoader.php @@ -168,5 +168,7 @@ abstract class FileLoader extends Loader throw new FileLoaderLoadException($resource, $sourceResource, null, $e, $type); } } + + return null; } } diff --git a/lib/symfony/config/Resource/ClassExistenceResource.php b/lib/symfony/config/Resource/ClassExistenceResource.php index 5554f4c67..1ba8e7624 100644 --- a/lib/symfony/config/Resource/ClassExistenceResource.php +++ b/lib/symfony/config/Resource/ClassExistenceResource.php @@ -76,10 +76,14 @@ class ClassExistenceResource implements SelfCheckingResourceInterface, \Serializ try { $exists = class_exists($this->resource) || interface_exists($this->resource, false) || trait_exists($this->resource, false); - } catch (\ReflectionException $e) { - if (0 >= $timestamp) { - unset(self::$existsCache[1][$this->resource]); - throw $e; + } catch (\Exception $e) { + try { + self::throwOnRequiredClass($this->resource, $e); + } catch (\ReflectionException $e) { + if (0 >= $timestamp) { + unset(self::$existsCache[1][$this->resource]); + throw $e; + } } } finally { self::$autoloadedClass = $autoloadedClass; @@ -117,24 +121,57 @@ class ClassExistenceResource implements SelfCheckingResourceInterface, \Serializ } /** - * @throws \ReflectionException When $class is not found and is required + * Throws a reflection exception when the passed class does not exist but is required. + * + * A class is considered "not required" when it's loaded as part of a "class_exists" or similar check. + * + * This function can be used as an autoload function to throw a reflection + * exception if the class was not found by previous autoload functions. + * + * A previous exception can be passed. In this case, the class is considered as being + * required totally, so if it doesn't exist, a reflection exception is always thrown. + * If it exists, the previous exception is rethrown. + * + * @throws \ReflectionException * * @internal */ - public static function throwOnRequiredClass($class) + public static function throwOnRequiredClass($class, \Exception $previous = null) { - if (self::$autoloadedClass === $class) { + // If the passed class is the resource being checked, we shouldn't throw. + if (null === $previous && self::$autoloadedClass === $class) { return; } - $e = new \ReflectionException("Class $class not found"); + + if (class_exists($class, false) || interface_exists($class, false) || trait_exists($class, false)) { + if (null !== $previous) { + throw $previous; + } + + return; + } + + if ($previous instanceof \ReflectionException) { + throw $previous; + } + + $e = new \ReflectionException(sprintf('Class "%s" not found while loading "%s".', $class, self::$autoloadedClass), 0, $previous); + + if (null !== $previous) { + throw $e; + } + $trace = $e->getTrace(); $autoloadFrame = [ 'function' => 'spl_autoload_call', 'args' => [$class], ]; - $i = 1 + array_search($autoloadFrame, $trace, true); - if (isset($trace[$i]['function']) && !isset($trace[$i]['class'])) { + if (false === $i = array_search($autoloadFrame, $trace, true)) { + throw $e; + } + + if (isset($trace[++$i]['function']) && !isset($trace[$i]['class'])) { switch ($trace[$i]['function']) { case 'get_class_methods': case 'get_class_vars': diff --git a/lib/symfony/config/Resource/GlobResource.php b/lib/symfony/config/Resource/GlobResource.php index 28ba0a611..13d2ee7d7 100644 --- a/lib/symfony/config/Resource/GlobResource.php +++ b/lib/symfony/config/Resource/GlobResource.php @@ -100,7 +100,9 @@ class GlobResource implements \IteratorAggregate, SelfCheckingResourceInterface, } if (0 !== strpos($this->prefix, 'phar://') && false === strpos($this->pattern, '/**/') && (\defined('GLOB_BRACE') || false === strpos($this->pattern, '{'))) { - foreach (glob($this->prefix.$this->pattern, \defined('GLOB_BRACE') ? GLOB_BRACE : 0) as $path) { + $paths = glob($this->prefix.$this->pattern, GLOB_NOSORT | (\defined('GLOB_BRACE') ? GLOB_BRACE : 0)); + sort($paths); + foreach ($paths as $path) { if ($this->recursive && is_dir($path)) { $files = iterator_to_array(new \RecursiveIteratorIterator( new \RecursiveCallbackFilterIterator( diff --git a/lib/symfony/config/Resource/ReflectionClassResource.php b/lib/symfony/config/Resource/ReflectionClassResource.php index f05042f8d..d5e6b829c 100644 --- a/lib/symfony/config/Resource/ReflectionClassResource.php +++ b/lib/symfony/config/Resource/ReflectionClassResource.php @@ -140,7 +140,7 @@ class ReflectionClassResource implements SelfCheckingResourceInterface, \Seriali foreach ($class->getProperties(\ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED) as $p) { yield $p->getDocComment().$p; - yield print_r(isset($defaults[$p->name]) ? $defaults[$p->name] : null, true); + yield print_r(isset($defaults[$p->name]) && !\is_object($defaults[$p->name]) ? $defaults[$p->name] : null, true); } } diff --git a/lib/symfony/config/Tests/ConfigCacheFactoryTest.php b/lib/symfony/config/Tests/ConfigCacheFactoryTest.php index 24e3224ce..6190b9b45 100644 --- a/lib/symfony/config/Tests/ConfigCacheFactoryTest.php +++ b/lib/symfony/config/Tests/ConfigCacheFactoryTest.php @@ -16,12 +16,10 @@ use Symfony\Component\Config\ConfigCacheFactory; class ConfigCacheFactoryTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid type for callback argument. Expected callable, but got "object". - */ public function testCacheWithInvalidCallback() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Invalid type for callback argument. Expected callable, but got "object".'); $cacheFactory = new ConfigCacheFactory(true); $cacheFactory->cache('file', new \stdClass()); diff --git a/lib/symfony/config/Tests/Definition/ArrayNodeTest.php b/lib/symfony/config/Tests/Definition/ArrayNodeTest.php index 8f84cff38..25c2cfc69 100644 --- a/lib/symfony/config/Tests/Definition/ArrayNodeTest.php +++ b/lib/symfony/config/Tests/Definition/ArrayNodeTest.php @@ -18,21 +18,17 @@ use Symfony\Component\Config\Definition\ScalarNode; class ArrayNodeTest extends TestCase { - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException - */ public function testNormalizeThrowsExceptionWhenFalseIsNotAllowed() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); $node = new ArrayNode('root'); $node->normalize(false); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage Unrecognized option "foo" under "root" - */ public function testExceptionThrownOnUnrecognizedChild() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('Unrecognized option "foo" under "root"'); $node = new ArrayNode('root'); $node->normalize(['foo' => 'bar']); } @@ -55,12 +51,8 @@ class ArrayNodeTest extends TestCase public function testIgnoreAndRemoveBehaviors($ignore, $remove, $expected, $message = '') { if ($expected instanceof \Exception) { - if (method_exists($this, 'expectException')) { - $this->expectException(\get_class($expected)); - $this->expectExceptionMessage($expected->getMessage()); - } else { - $this->setExpectedException(\get_class($expected), $expected->getMessage()); - } + $this->expectException(\get_class($expected)); + $this->expectExceptionMessage($expected->getMessage()); } $node = new ArrayNode('root'); $node->setIgnoreExtraKeys($ignore, $remove); @@ -180,24 +172,20 @@ class ArrayNodeTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Child nodes must be named. - */ public function testAddChildEmptyName() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Child nodes must be named.'); $node = new ArrayNode('root'); $childNode = new ArrayNode(''); $node->addChild($childNode); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage A child node named "foo" already exists. - */ public function testAddChildNameAlreadyExists() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('A child node named "foo" already exists.'); $node = new ArrayNode('root'); $childNode = new ArrayNode('foo'); @@ -207,12 +195,10 @@ class ArrayNodeTest extends TestCase $node->addChild($childNodeWithSameName); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage The node at path "foo" has no default value. - */ public function testGetDefaultValueWithoutDefaultValue() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('The node at path "foo" has no default value.'); $node = new ArrayNode('foo'); $node->getDefaultValue(); } diff --git a/lib/symfony/config/Tests/Definition/BooleanNodeTest.php b/lib/symfony/config/Tests/Definition/BooleanNodeTest.php index bfa2fd3e2..8552eeba3 100644 --- a/lib/symfony/config/Tests/Definition/BooleanNodeTest.php +++ b/lib/symfony/config/Tests/Definition/BooleanNodeTest.php @@ -48,10 +48,10 @@ class BooleanNodeTest extends TestCase /** * @dataProvider getInvalidValues - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); $node = new BooleanNode('test'); $node->normalize($value); } diff --git a/lib/symfony/config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php b/lib/symfony/config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php index 4ad7eabf3..1123b4159 100644 --- a/lib/symfony/config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php +++ b/lib/symfony/config/Tests/Definition/Builder/ArrayNodeDefinitionTest.php @@ -36,11 +36,11 @@ class ArrayNodeDefinitionTest extends TestCase } /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException * @dataProvider providePrototypeNodeSpecificCalls */ public function testPrototypeNodeSpecificOption($method, $args) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); $node = new ArrayNodeDefinition('root'); \call_user_func_array([$node, $method], $args); @@ -58,11 +58,9 @@ class ArrayNodeDefinitionTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException - */ public function testConcreteNodeSpecificOption() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); $node = new ArrayNodeDefinition('root'); $node ->addDefaultsIfNotSet() @@ -71,11 +69,9 @@ class ArrayNodeDefinitionTest extends TestCase $node->getNode(); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException - */ public function testPrototypeNodesCantHaveADefaultValueWhenUsingDefaultChildren() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); $node = new ArrayNodeDefinition('root'); $node ->defaultValue([]) diff --git a/lib/symfony/config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php b/lib/symfony/config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php index c0d347f3d..6f568a2df 100644 --- a/lib/symfony/config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php +++ b/lib/symfony/config/Tests/Definition/Builder/BooleanNodeDefinitionTest.php @@ -16,12 +16,10 @@ use Symfony\Component\Config\Definition\Builder\BooleanNodeDefinition; class BooleanNodeDefinitionTest extends TestCase { - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException - * @expectedExceptionMessage ->cannotBeEmpty() is not applicable to BooleanNodeDefinition. - */ public function testCannotBeEmptyThrowsAnException() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); + $this->expectExceptionMessage('->cannotBeEmpty() is not applicable to BooleanNodeDefinition.'); $def = new BooleanNodeDefinition('foo'); $def->cannotBeEmpty(); } diff --git a/lib/symfony/config/Tests/Definition/Builder/EnumNodeDefinitionTest.php b/lib/symfony/config/Tests/Definition/Builder/EnumNodeDefinitionTest.php index 26f8586dc..2e43a1354 100644 --- a/lib/symfony/config/Tests/Definition/Builder/EnumNodeDefinitionTest.php +++ b/lib/symfony/config/Tests/Definition/Builder/EnumNodeDefinitionTest.php @@ -34,22 +34,18 @@ class EnumNodeDefinitionTest extends TestCase $this->assertEquals(['foo'], $node->getValues()); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage You must call ->values() on enum nodes. - */ public function testNoValuesPassed() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('You must call ->values() on enum nodes.'); $def = new EnumNodeDefinition('foo'); $def->getNode(); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage ->values() must be called with at least one value. - */ public function testWithNoValues() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('->values() must be called with at least one value.'); $def = new EnumNodeDefinition('foo'); $def->values([]); } diff --git a/lib/symfony/config/Tests/Definition/Builder/ExprBuilderTest.php b/lib/symfony/config/Tests/Definition/Builder/ExprBuilderTest.php index 191bf1c0b..85d0d3631 100644 --- a/lib/symfony/config/Tests/Definition/Builder/ExprBuilderTest.php +++ b/lib/symfony/config/Tests/Definition/Builder/ExprBuilderTest.php @@ -164,11 +164,9 @@ class ExprBuilderTest extends TestCase yield [['value'], ['value']]; } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - */ public function testThenInvalid() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $test = $this->getTestBuilder() ->ifString() ->thenInvalid('Invalid value') @@ -185,21 +183,17 @@ class ExprBuilderTest extends TestCase $this->assertEquals([], $this->finalizeTestBuilder($test)); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage You must specify an if part. - */ public function testEndIfPartNotSpecified() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('You must specify an if part.'); $this->getTestBuilder()->end(); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage You must specify a then part. - */ public function testEndThenPartNotSpecified() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('You must specify a then part.'); $builder = $this->getTestBuilder(); $builder->ifPart = 'test'; $builder->end(); diff --git a/lib/symfony/config/Tests/Definition/Builder/NodeBuilderTest.php b/lib/symfony/config/Tests/Definition/Builder/NodeBuilderTest.php index cd77dd702..5cc7cfea4 100644 --- a/lib/symfony/config/Tests/Definition/Builder/NodeBuilderTest.php +++ b/lib/symfony/config/Tests/Definition/Builder/NodeBuilderTest.php @@ -17,20 +17,16 @@ use Symfony\Component\Config\Definition\Builder\VariableNodeDefinition as BaseVa class NodeBuilderTest extends TestCase { - /** - * @expectedException \RuntimeException - */ public function testThrowsAnExceptionWhenTryingToCreateANonRegisteredNodeType() { + $this->expectException('RuntimeException'); $builder = new BaseNodeBuilder(); $builder->node('', 'foobar'); } - /** - * @expectedException \RuntimeException - */ public function testThrowsAnExceptionWhenTheNodeClassIsNotFound() { + $this->expectException('RuntimeException'); $builder = new BaseNodeBuilder(); $builder ->setNodeClass('noclasstype', '\\foo\\bar\\noclass') diff --git a/lib/symfony/config/Tests/Definition/Builder/NumericNodeDefinitionTest.php b/lib/symfony/config/Tests/Definition/Builder/NumericNodeDefinitionTest.php index 31342503d..aa938bbaa 100644 --- a/lib/symfony/config/Tests/Definition/Builder/NumericNodeDefinitionTest.php +++ b/lib/symfony/config/Tests/Definition/Builder/NumericNodeDefinitionTest.php @@ -14,46 +14,37 @@ namespace Symfony\Component\Config\Tests\Definition\Builder; use PHPUnit\Framework\TestCase; use Symfony\Component\Config\Definition\Builder\FloatNodeDefinition; use Symfony\Component\Config\Definition\Builder\IntegerNodeDefinition; -use Symfony\Component\Config\Definition\Builder\IntegerNodeDefinition as NumericNodeDefinition; class NumericNodeDefinitionTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage You cannot define a min(4) as you already have a max(3) - */ public function testIncoherentMinAssertion() { - $def = new NumericNodeDefinition('foo'); + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('You cannot define a min(4) as you already have a max(3)'); + $def = new IntegerNodeDefinition('foo'); $def->max(3)->min(4); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage You cannot define a max(2) as you already have a min(3) - */ public function testIncoherentMaxAssertion() { - $node = new NumericNodeDefinition('foo'); + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('You cannot define a max(2) as you already have a min(3)'); + $node = new IntegerNodeDefinition('foo'); $node->min(3)->max(2); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The value 4 is too small for path "foo". Should be greater than or equal to 5 - */ public function testIntegerMinAssertion() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('The value 4 is too small for path "foo". Should be greater than or equal to 5'); $def = new IntegerNodeDefinition('foo'); $def->min(5)->getNode()->finalize(4); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The value 4 is too big for path "foo". Should be less than or equal to 3 - */ public function testIntegerMaxAssertion() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('The value 4 is too big for path "foo". Should be less than or equal to 3'); $def = new IntegerNodeDefinition('foo'); $def->max(3)->getNode()->finalize(4); } @@ -65,22 +56,18 @@ class NumericNodeDefinitionTest extends TestCase $this->assertEquals(4, $node->finalize(4)); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The value 400 is too small for path "foo". Should be greater than or equal to 500 - */ public function testFloatMinAssertion() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('The value 400 is too small for path "foo". Should be greater than or equal to 500'); $def = new FloatNodeDefinition('foo'); $def->min(5E2)->getNode()->finalize(4e2); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The value 4.3 is too big for path "foo". Should be less than or equal to 0.3 - */ public function testFloatMaxAssertion() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('The value 4.3 is too big for path "foo". Should be less than or equal to 0.3'); $def = new FloatNodeDefinition('foo'); $def->max(0.3)->getNode()->finalize(4.3); } @@ -92,13 +79,11 @@ class NumericNodeDefinitionTest extends TestCase $this->assertEquals(4.5, $node->finalize(4.5)); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidDefinitionException - * @expectedExceptionMessage ->cannotBeEmpty() is not applicable to NumericNodeDefinition. - */ public function testCannotBeEmptyThrowsAnException() { - $def = new NumericNodeDefinition('foo'); + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidDefinitionException'); + $this->expectExceptionMessage('->cannotBeEmpty() is not applicable to NumericNodeDefinition.'); + $def = new IntegerNodeDefinition('foo'); $def->cannotBeEmpty(); } } diff --git a/lib/symfony/config/Tests/Definition/Builder/TreeBuilderTest.php b/lib/symfony/config/Tests/Definition/Builder/TreeBuilderTest.php index d94912b78..53c9c256b 100644 --- a/lib/symfony/config/Tests/Definition/Builder/TreeBuilderTest.php +++ b/lib/symfony/config/Tests/Definition/Builder/TreeBuilderTest.php @@ -128,7 +128,7 @@ class TreeBuilderTest extends TestCase $tree = $builder->buildTree(); $children = $tree->getChildren(); - $this->assertInternalType('array', $tree->getExample()); + $this->assertIsArray($tree->getExample()); $this->assertEquals('example', $children['child']->getExample()); } } diff --git a/lib/symfony/config/Tests/Definition/EnumNodeTest.php b/lib/symfony/config/Tests/Definition/EnumNodeTest.php index 206bfdd5b..fa89eea23 100644 --- a/lib/symfony/config/Tests/Definition/EnumNodeTest.php +++ b/lib/symfony/config/Tests/Definition/EnumNodeTest.php @@ -22,12 +22,10 @@ class EnumNodeTest extends TestCase $this->assertSame('foo', $node->finalize('foo')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage $values must contain at least one element. - */ public function testConstructionWithNoValues() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('$values must contain at least one element.'); new EnumNode('foo', null, []); } @@ -43,12 +41,10 @@ class EnumNodeTest extends TestCase $this->assertSame('foo', $node->finalize('foo')); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The value "foobar" is not allowed for path "foo". Permissible values: "foo", "bar" - */ public function testFinalizeWithInvalidValue() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('The value "foobar" is not allowed for path "foo". Permissible values: "foo", "bar"'); $node = new EnumNode('foo', null, ['foo', 'bar']); $node->finalize('foobar'); } diff --git a/lib/symfony/config/Tests/Definition/FloatNodeTest.php b/lib/symfony/config/Tests/Definition/FloatNodeTest.php index 8268fe83b..fed9f013d 100644 --- a/lib/symfony/config/Tests/Definition/FloatNodeTest.php +++ b/lib/symfony/config/Tests/Definition/FloatNodeTest.php @@ -54,10 +54,10 @@ class FloatNodeTest extends TestCase /** * @dataProvider getInvalidValues - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); $node = new FloatNode('test'); $node->normalize($value); } diff --git a/lib/symfony/config/Tests/Definition/IntegerNodeTest.php b/lib/symfony/config/Tests/Definition/IntegerNodeTest.php index b4c17e1cb..3fb1b771e 100644 --- a/lib/symfony/config/Tests/Definition/IntegerNodeTest.php +++ b/lib/symfony/config/Tests/Definition/IntegerNodeTest.php @@ -49,10 +49,10 @@ class IntegerNodeTest extends TestCase /** * @dataProvider getInvalidValues - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); $node = new IntegerNode('test'); $node->normalize($value); } diff --git a/lib/symfony/config/Tests/Definition/MergeTest.php b/lib/symfony/config/Tests/Definition/MergeTest.php index 5d37e137b..8fee2635c 100644 --- a/lib/symfony/config/Tests/Definition/MergeTest.php +++ b/lib/symfony/config/Tests/Definition/MergeTest.php @@ -16,11 +16,9 @@ use Symfony\Component\Config\Definition\Builder\TreeBuilder; class MergeTest extends TestCase { - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\ForbiddenOverwriteException - */ public function testForbiddenOverwrite() { + $this->expectException('Symfony\Component\Config\Definition\Exception\ForbiddenOverwriteException'); $tb = new TreeBuilder(); $tree = $tb ->root('root', 'array') @@ -92,11 +90,9 @@ class MergeTest extends TestCase ], $tree->merge($a, $b)); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - */ public function testDoesNotAllowNewKeysInSubsequentConfigs() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $tb = new TreeBuilder(); $tree = $tb ->root('config', 'array') diff --git a/lib/symfony/config/Tests/Definition/NormalizationTest.php b/lib/symfony/config/Tests/Definition/NormalizationTest.php index d6544ccc8..200a98594 100644 --- a/lib/symfony/config/Tests/Definition/NormalizationTest.php +++ b/lib/symfony/config/Tests/Definition/NormalizationTest.php @@ -169,12 +169,10 @@ class NormalizationTest extends TestCase return array_map(function ($v) { return [$v]; }, $configs); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage The attribute "id" must be set for path "root.thing". - */ public function testNonAssociativeArrayThrowsExceptionIfAttributeNotSet() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('The attribute "id" must be set for path "root.thing".'); $denormalized = [ 'thing' => [ ['foo', 'bar'], ['baz', 'qux'], diff --git a/lib/symfony/config/Tests/Definition/PrototypedArrayNodeTest.php b/lib/symfony/config/Tests/Definition/PrototypedArrayNodeTest.php index 6478bd12d..7a58ead8d 100644 --- a/lib/symfony/config/Tests/Definition/PrototypedArrayNodeTest.php +++ b/lib/symfony/config/Tests/Definition/PrototypedArrayNodeTest.php @@ -262,7 +262,6 @@ class PrototypedArrayNodeTest extends TestCase * ] * ] * - * * @dataProvider getDataForKeyRemovedLeftValueOnly */ public function testMappedAttributeKeyIsRemovedLeftValueOnly($value, $children, $expected) diff --git a/lib/symfony/config/Tests/Definition/ScalarNodeTest.php b/lib/symfony/config/Tests/Definition/ScalarNodeTest.php index ada5b04be..4413baf3c 100644 --- a/lib/symfony/config/Tests/Definition/ScalarNodeTest.php +++ b/lib/symfony/config/Tests/Definition/ScalarNodeTest.php @@ -74,10 +74,10 @@ class ScalarNodeTest extends TestCase /** * @dataProvider getInvalidValues - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidTypeException */ public function testNormalizeThrowsExceptionOnInvalidValues($value) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); $node = new ScalarNode('test'); $node->normalize($value); } @@ -95,12 +95,8 @@ class ScalarNodeTest extends TestCase { $node = new ScalarNode('test'); - if (method_exists($this, 'expectException')) { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); - $this->expectExceptionMessage('Invalid type for path "test". Expected scalar, but got array.'); - } else { - $this->setExpectedException('Symfony\Component\Config\Definition\Exception\InvalidTypeException', 'Invalid type for path "test". Expected scalar, but got array.'); - } + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); + $this->expectExceptionMessage('Invalid type for path "test". Expected scalar, but got array.'); $node->normalize([]); } @@ -110,12 +106,8 @@ class ScalarNodeTest extends TestCase $node = new ScalarNode('test'); $node->setInfo('"the test value"'); - if (method_exists($this, 'expectException')) { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); - $this->expectExceptionMessage("Invalid type for path \"test\". Expected scalar, but got array.\nHint: \"the test value\""); - } else { - $this->setExpectedException('Symfony\Component\Config\Definition\Exception\InvalidTypeException', "Invalid type for path \"test\". Expected scalar, but got array.\nHint: \"the test value\""); - } + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidTypeException'); + $this->expectExceptionMessage("Invalid type for path \"test\". Expected scalar, but got array.\nHint: \"the test value\""); $node->normalize([]); } @@ -148,12 +140,12 @@ class ScalarNodeTest extends TestCase /** * @dataProvider getEmptyValues - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException * * @param mixed $value */ public function testNotAllowedEmptyValuesThrowException($value) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $node = new ScalarNode('test'); $node->setAllowEmptyValue(false); $node->finalize($value); diff --git a/lib/symfony/config/Tests/FileLocatorTest.php b/lib/symfony/config/Tests/FileLocatorTest.php index 0bd97f7d8..e931916af 100644 --- a/lib/symfony/config/Tests/FileLocatorTest.php +++ b/lib/symfony/config/Tests/FileLocatorTest.php @@ -86,33 +86,27 @@ class FileLocatorTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\Config\Exception\FileLocatorFileNotFoundException - * @expectedExceptionMessage The file "foobar.xml" does not exist - */ public function testLocateThrowsAnExceptionIfTheFileDoesNotExists() { + $this->expectException('Symfony\Component\Config\Exception\FileLocatorFileNotFoundException'); + $this->expectExceptionMessage('The file "foobar.xml" does not exist'); $loader = new FileLocator([__DIR__.'/Fixtures']); $loader->locate('foobar.xml', __DIR__); } - /** - * @expectedException \Symfony\Component\Config\Exception\FileLocatorFileNotFoundException - */ public function testLocateThrowsAnExceptionIfTheFileDoesNotExistsInAbsolutePath() { + $this->expectException('Symfony\Component\Config\Exception\FileLocatorFileNotFoundException'); $loader = new FileLocator([__DIR__.'/Fixtures']); $loader->locate(__DIR__.'/Fixtures/foobar.xml', __DIR__); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage An empty file name is not valid to be located. - */ public function testLocateEmpty() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('An empty file name is not valid to be located.'); $loader = new FileLocator([__DIR__.'/Fixtures']); $loader->locate(null, __DIR__); diff --git a/lib/symfony/config/Tests/Loader/DelegatingLoaderTest.php b/lib/symfony/config/Tests/Loader/DelegatingLoaderTest.php index 6556962d1..38ae6ff7b 100644 --- a/lib/symfony/config/Tests/Loader/DelegatingLoaderTest.php +++ b/lib/symfony/config/Tests/Loader/DelegatingLoaderTest.php @@ -19,7 +19,7 @@ class DelegatingLoaderTest extends TestCase { public function testConstructor() { - $loader = new DelegatingLoader($resolver = new LoaderResolver()); + new DelegatingLoader($resolver = new LoaderResolver()); $this->assertTrue(true, '__construct() takes a loader resolver as its first argument'); } @@ -56,11 +56,9 @@ class DelegatingLoaderTest extends TestCase $loader->load('foo'); } - /** - * @expectedException \Symfony\Component\Config\Exception\FileLoaderLoadException - */ public function testLoadThrowsAnExceptionIfTheResourceCannotBeLoaded() { + $this->expectException('Symfony\Component\Config\Exception\FileLoaderLoadException'); $loader = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderInterface')->getMock(); $loader->expects($this->once())->method('supports')->willReturn(false); $resolver = new LoaderResolver([$loader]); diff --git a/lib/symfony/config/Tests/Loader/LoaderTest.php b/lib/symfony/config/Tests/Loader/LoaderTest.php index 0c6e3fc02..35a911ef3 100644 --- a/lib/symfony/config/Tests/Loader/LoaderTest.php +++ b/lib/symfony/config/Tests/Loader/LoaderTest.php @@ -43,11 +43,9 @@ class LoaderTest extends TestCase $this->assertSame($resolvedLoader, $loader->resolve('foo.xml'), '->resolve() finds a loader'); } - /** - * @expectedException \Symfony\Component\Config\Exception\FileLoaderLoadException - */ public function testResolveWhenResolverCannotFindLoader() { + $this->expectException('Symfony\Component\Config\Exception\FileLoaderLoadException'); $resolver = $this->getMockBuilder('Symfony\Component\Config\Loader\LoaderResolverInterface')->getMock(); $resolver->expects($this->once()) ->method('resolve') diff --git a/lib/symfony/config/Tests/Resource/ClassExistenceResourceTest.php b/lib/symfony/config/Tests/Resource/ClassExistenceResourceTest.php index 79bc64d69..b7ae81eaa 100644 --- a/lib/symfony/config/Tests/Resource/ClassExistenceResourceTest.php +++ b/lib/symfony/config/Tests/Resource/ClassExistenceResourceTest.php @@ -67,7 +67,7 @@ EOF $loadedClass = 123; - $res = new ClassExistenceResource('MissingFooClass', false); + new ClassExistenceResource('MissingFooClass', false); $this->assertSame(123, $loadedClass); } finally { @@ -81,12 +81,11 @@ EOF $this->assertTrue($res->isFresh(time())); } - /** - * @expectedException \ReflectionException - * @expectedExceptionMessage Class Symfony\Component\Config\Tests\Fixtures\MissingParent not found - */ public function testBadParentWithNoTimestamp() { + $this->expectException('ReflectionException'); + $this->expectExceptionMessage('Class "Symfony\Component\Config\Tests\Fixtures\MissingParent" not found while loading "Symfony\Component\Config\Tests\Fixtures\BadParent".'); + $res = new ClassExistenceResource(BadParent::class, false); $res->isFresh(0); } diff --git a/lib/symfony/config/Tests/Resource/DirectoryResourceTest.php b/lib/symfony/config/Tests/Resource/DirectoryResourceTest.php index 85f6c02ee..40b179010 100644 --- a/lib/symfony/config/Tests/Resource/DirectoryResourceTest.php +++ b/lib/symfony/config/Tests/Resource/DirectoryResourceTest.php @@ -63,13 +63,11 @@ class DirectoryResourceTest extends TestCase $this->assertEquals('bar', $resource->getPattern()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /The directory ".*" does not exist./ - */ public function testResourceDoesNotExist() { - $resource = new DirectoryResource('/____foo/foobar'.mt_rand(1, 999999)); + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The directory ".*" does not exist./'); + new DirectoryResource('/____foo/foobar'.mt_rand(1, 999999)); } public function testIsFresh() @@ -167,7 +165,7 @@ class DirectoryResourceTest extends TestCase { $resource = new DirectoryResource($this->directory, '/\.(foo|xml)$/'); - $unserialized = unserialize(serialize($resource)); + unserialize(serialize($resource)); $this->assertSame(realpath($this->directory), $resource->getResource()); $this->assertSame('/\.(foo|xml)$/', $resource->getPattern()); diff --git a/lib/symfony/config/Tests/Resource/FileResourceTest.php b/lib/symfony/config/Tests/Resource/FileResourceTest.php index 97781ffab..968c7e926 100644 --- a/lib/symfony/config/Tests/Resource/FileResourceTest.php +++ b/lib/symfony/config/Tests/Resource/FileResourceTest.php @@ -53,13 +53,11 @@ class FileResourceTest extends TestCase $this->assertSame(realpath($this->file), (string) $this->resource); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /The file ".*" does not exist./ - */ public function testResourceDoesNotExist() { - $resource = new FileResource('/____foo/foobar'.mt_rand(1, 999999)); + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The file ".*" does not exist./'); + new FileResource('/____foo/foobar'.mt_rand(1, 999999)); } public function testIsFresh() @@ -78,7 +76,7 @@ class FileResourceTest extends TestCase public function testSerializeUnserialize() { - $unserialized = unserialize(serialize($this->resource)); + unserialize(serialize($this->resource)); $this->assertSame(realpath($this->file), $this->resource->getResource()); } diff --git a/lib/symfony/config/Tests/Resource/ReflectionClassResourceTest.php b/lib/symfony/config/Tests/Resource/ReflectionClassResourceTest.php index 1f0bcb17b..76cad1433 100644 --- a/lib/symfony/config/Tests/Resource/ReflectionClassResourceTest.php +++ b/lib/symfony/config/Tests/Resource/ReflectionClassResourceTest.php @@ -170,6 +170,15 @@ EOPHP; $res = new ReflectionClassResource(new \ReflectionClass(TestServiceSubscriber::class)); $this->assertTrue($res->isFresh(0)); } + + public function testIgnoresObjectsInSignature() + { + $res = new ReflectionClassResource(new \ReflectionClass(TestServiceWithStaticProperty::class)); + $this->assertTrue($res->isFresh(0)); + + TestServiceWithStaticProperty::$initializedObject = new TestServiceWithStaticProperty(); + $this->assertTrue($res->isFresh(0)); + } } interface DummyInterface @@ -195,3 +204,8 @@ class TestServiceSubscriber implements ServiceSubscriberInterface return self::$subscribedServices; } } + +class TestServiceWithStaticProperty +{ + public static $initializedObject; +} diff --git a/lib/symfony/config/Tests/Util/XmlUtilsTest.php b/lib/symfony/config/Tests/Util/XmlUtilsTest.php index 0a6637f78..4653c8d7c 100644 --- a/lib/symfony/config/Tests/Util/XmlUtilsTest.php +++ b/lib/symfony/config/Tests/Util/XmlUtilsTest.php @@ -24,28 +24,28 @@ class XmlUtilsTest extends TestCase XmlUtils::loadFile($fixtures.'invalid.xml'); $this->fail(); } catch (\InvalidArgumentException $e) { - $this->assertContains('ERROR 77', $e->getMessage()); + $this->assertStringContainsString('ERROR 77', $e->getMessage()); } try { XmlUtils::loadFile($fixtures.'document_type.xml'); $this->fail(); } catch (\InvalidArgumentException $e) { - $this->assertContains('Document types are not allowed', $e->getMessage()); + $this->assertStringContainsString('Document types are not allowed', $e->getMessage()); } try { XmlUtils::loadFile($fixtures.'invalid_schema.xml', $fixtures.'schema.xsd'); $this->fail(); } catch (\InvalidArgumentException $e) { - $this->assertContains('ERROR 1845', $e->getMessage()); + $this->assertStringContainsString('ERROR 1845', $e->getMessage()); } try { XmlUtils::loadFile($fixtures.'invalid_schema.xml', 'invalid_callback_or_file'); $this->fail(); } catch (\InvalidArgumentException $e) { - $this->assertContains('XSD file or callable', $e->getMessage()); + $this->assertStringContainsString('XSD file or callable', $e->getMessage()); } $mock = $this->getMockBuilder(__NAMESPACE__.'\Validator')->getMock(); @@ -62,12 +62,10 @@ class XmlUtilsTest extends TestCase $this->assertSame([], libxml_get_errors()); } - /** - * @expectedException \Symfony\Component\Config\Util\Exception\InvalidXmlException - * @expectedExceptionMessage The XML is not valid - */ public function testParseWithInvalidValidatorCallable() { + $this->expectException('Symfony\Component\Config\Util\Exception\InvalidXmlException'); + $this->expectExceptionMessage('The XML is not valid'); $fixtures = __DIR__.'/../Fixtures/Util/'; $mock = $this->getMockBuilder(__NAMESPACE__.'\Validator')->getMock(); @@ -166,12 +164,8 @@ class XmlUtilsTest extends TestCase { $file = __DIR__.'/../Fixtures/foo.xml'; - if (method_exists($this, 'expectException')) { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage(sprintf('File %s does not contain valid XML, it is empty.', $file)); - } else { - $this->setExpectedException('InvalidArgumentException', sprintf('File %s does not contain valid XML, it is empty.', $file)); - } + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage(sprintf('File %s does not contain valid XML, it is empty.', $file)); XmlUtils::loadFile($file); } diff --git a/lib/symfony/config/Util/XmlUtils.php b/lib/symfony/config/Util/XmlUtils.php index df1edd68b..d0042af30 100644 --- a/lib/symfony/config/Util/XmlUtils.php +++ b/lib/symfony/config/Util/XmlUtils.php @@ -152,7 +152,7 @@ class XmlUtils * @param \DOMElement $element A \DOMElement instance * @param bool $checkPrefix Check prefix in an element or an attribute name * - * @return array A PHP array + * @return mixed */ public static function convertDomElementToArray(\DOMElement $element, $checkPrefix = true) { @@ -219,7 +219,7 @@ class XmlUtils switch (true) { case 'null' === $lowercaseValue: - return; + return null; case ctype_digit($value): $raw = $value; $cast = (int) $value; @@ -234,7 +234,7 @@ class XmlUtils return true; case 'false' === $lowercaseValue: return false; - case isset($value[1]) && '0b' == $value[0].$value[1]: + case isset($value[1]) && '0b' == $value[0].$value[1] && preg_match('/^0b[01]*$/', $value): return bindec($value); case is_numeric($value): return '0x' === $value[0].$value[1] ? hexdec($value) : (float) $value; diff --git a/lib/symfony/console/Application.php b/lib/symfony/console/Application.php index 4d10c3169..d181e41e8 100644 --- a/lib/symfony/console/Application.php +++ b/lib/symfony/console/Application.php @@ -454,12 +454,11 @@ class Application if (!$command->isEnabled()) { $command->setApplication(null); - return; + return null; } - if (null === $command->getDefinition()) { - throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', \get_class($command))); - } + // Will throw if the command is not correctly initialized. + $command->getDefinition(); if (!$command->getName()) { throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', \get_class($command))); @@ -530,6 +529,10 @@ class Application { $namespaces = []; foreach ($this->all() as $command) { + if ($command->isHidden()) { + continue; + } + $namespaces = array_merge($namespaces, $this->extractAllNamespaces($command->getName())); foreach ($command->getAliases() as $alias) { @@ -623,6 +626,11 @@ class Application $message = sprintf('Command "%s" is not defined.', $name); if ($alternatives = $this->findAlternatives($name, $allCommands)) { + // remove hidden commands + $alternatives = array_filter($alternatives, function ($name) { + return !$this->get($name)->isHidden(); + }); + if (1 == \count($alternatives)) { $message .= "\n\nDid you mean this?\n "; } else { @@ -631,7 +639,7 @@ class Application $message .= implode("\n ", $alternatives); } - throw new CommandNotFoundException($message, $alternatives); + throw new CommandNotFoundException($message, array_values($alternatives)); } // filter out aliases for commands which are already on the list @@ -655,13 +663,18 @@ class Application } $abbrevs = array_map(function ($cmd) use ($commandList, $usableWidth, $maxLen) { if (!$commandList[$cmd] instanceof Command) { - return $cmd; + $commandList[$cmd] = $this->commandLoader->get($cmd); } + + if ($commandList[$cmd]->isHidden()) { + return false; + } + $abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription(); return Helper::strlen($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev; }, array_values($commands)); - $suggestions = $this->getAbbreviationSuggestions($abbrevs); + $suggestions = $this->getAbbreviationSuggestions(array_filter($abbrevs)); throw new CommandNotFoundException(sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s", $name, $suggestions), array_values($commands)); } @@ -809,11 +822,11 @@ class Application for ($i = 0, $count = \count($trace); $i < $count; ++$i) { $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : ''; $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : ''; - $function = $trace[$i]['function']; + $function = isset($trace[$i]['function']) ? $trace[$i]['function'] : ''; $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a'; $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a'; - $output->writeln(sprintf(' %s%s%s() at %s:%s', $class, $type, $function, $file, $line), OutputInterface::VERBOSITY_QUIET); + $output->writeln(sprintf(' %s%s at %s:%s', $class, $function ? $type.$function.'()' : '', $file, $line), OutputInterface::VERBOSITY_QUIET); } $output->writeln('', OutputInterface::VERBOSITY_QUIET); @@ -1023,7 +1036,7 @@ class Application /** * Gets the name of the command based on input. * - * @return string The command name + * @return string|null */ protected function getCommandName(InputInterface $input) { @@ -1099,8 +1112,7 @@ class Application */ public function extractNamespace($name, $limit = null) { - $parts = explode(':', $name); - array_pop($parts); + $parts = explode(':', $name, -1); return implode(':', null === $limit ? $parts : \array_slice($parts, 0, $limit)); } diff --git a/lib/symfony/console/CHANGELOG.md b/lib/symfony/console/CHANGELOG.md index 946ff1e0b..6dba1a4de 100644 --- a/lib/symfony/console/CHANGELOG.md +++ b/lib/symfony/console/CHANGELOG.md @@ -22,7 +22,7 @@ CHANGELOG with value optional explicitly passed empty * added console.error event to catch exceptions thrown by other listeners * deprecated console.exception event in favor of console.error -* added ability to handle `CommandNotFoundException` through the +* added ability to handle `CommandNotFoundException` through the `console.error` event * deprecated default validation in `SymfonyQuestionHelper::ask` @@ -38,7 +38,7 @@ CHANGELOG ----- * added truncate method to FormatterHelper - * added setColumnWidth(s) method to Table + * added setColumnWidth(s) method to Table 2.8.3 ----- diff --git a/lib/symfony/console/Command/Command.php b/lib/symfony/console/Command/Command.php index 5f30da7a2..493800b31 100644 --- a/lib/symfony/console/Command/Command.php +++ b/lib/symfony/console/Command/Command.php @@ -40,8 +40,8 @@ class Command private $aliases = []; private $definition; private $hidden = false; - private $help; - private $description; + private $help = ''; + private $description = ''; private $ignoreValidationErrors = false; private $applicationDefinitionMerged = false; private $applicationDefinitionMergedWithArgs = false; @@ -105,7 +105,7 @@ class Command /** * Gets the helper set. * - * @return HelperSet A HelperSet instance + * @return HelperSet|null A HelperSet instance */ public function getHelperSet() { @@ -115,7 +115,7 @@ class Command /** * Gets the application instance for this command. * - * @return Application An Application instance + * @return Application|null An Application instance */ public function getApplication() { @@ -278,7 +278,7 @@ class Command $r = new \ReflectionFunction($code); if (null === $r->getClosureThis()) { if (\PHP_VERSION_ID < 70000) { - // Bug in PHP5: https://bugs.php.net/bug.php?id=64761 + // Bug in PHP5: https://bugs.php.net/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 // bindable. @@ -347,6 +347,10 @@ class Command */ public function getDefinition() { + if (null === $this->definition) { + throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', \get_class($this))); + } + return $this->definition; } @@ -449,7 +453,7 @@ class Command /** * Returns the command name. * - * @return string The command name + * @return string|null */ public function getName() { diff --git a/lib/symfony/console/Descriptor/ApplicationDescription.php b/lib/symfony/console/Descriptor/ApplicationDescription.php index 79a358fb3..442a56971 100644 --- a/lib/symfony/console/Descriptor/ApplicationDescription.php +++ b/lib/symfony/console/Descriptor/ApplicationDescription.php @@ -44,7 +44,6 @@ class ApplicationDescription private $aliases; /** - * @param Application $application * @param string|null $namespace * @param bool $showHidden */ diff --git a/lib/symfony/console/Descriptor/DescriptorInterface.php b/lib/symfony/console/Descriptor/DescriptorInterface.php index fbc07df87..e3184a6a5 100644 --- a/lib/symfony/console/Descriptor/DescriptorInterface.php +++ b/lib/symfony/console/Descriptor/DescriptorInterface.php @@ -23,9 +23,7 @@ interface DescriptorInterface /** * Describes an object if supported. * - * @param OutputInterface $output - * @param object $object - * @param array $options + * @param object $object */ public function describe(OutputInterface $output, $object, array $options = []); } diff --git a/lib/symfony/console/Descriptor/JsonDescriptor.php b/lib/symfony/console/Descriptor/JsonDescriptor.php index f5a143800..d1af3bab2 100644 --- a/lib/symfony/console/Descriptor/JsonDescriptor.php +++ b/lib/symfony/console/Descriptor/JsonDescriptor.php @@ -92,8 +92,6 @@ class JsonDescriptor extends Descriptor /** * Writes data as json. - * - * @return array|string */ private function writeData(array $data, array $options) { diff --git a/lib/symfony/console/Descriptor/XmlDescriptor.php b/lib/symfony/console/Descriptor/XmlDescriptor.php index 0cc0c9901..2d2545864 100644 --- a/lib/symfony/console/Descriptor/XmlDescriptor.php +++ b/lib/symfony/console/Descriptor/XmlDescriptor.php @@ -81,7 +81,6 @@ class XmlDescriptor extends Descriptor } /** - * @param Application $application * @param string|null $namespace * * @return \DOMDocument @@ -179,8 +178,6 @@ class XmlDescriptor extends Descriptor /** * Writes DOM document. - * - * @return \DOMDocument|string */ private function writeDocument(\DOMDocument $dom) { diff --git a/lib/symfony/console/EventListener/ErrorListener.php b/lib/symfony/console/EventListener/ErrorListener.php index 212ad1d96..783c10793 100644 --- a/lib/symfony/console/EventListener/ErrorListener.php +++ b/lib/symfony/console/EventListener/ErrorListener.php @@ -40,7 +40,9 @@ class ErrorListener implements EventSubscriberInterface $error = $event->getError(); if (!$inputString = $this->getInputString($event)) { - return $this->logger->error('An error occurred while using the console. Message: "{message}"', ['exception' => $error, 'message' => $error->getMessage()]); + $this->logger->error('An error occurred while using the console. Message: "{message}"', ['exception' => $error, 'message' => $error->getMessage()]); + + return; } $this->logger->error('Error thrown while running command "{command}". Message: "{message}"', ['exception' => $error, 'command' => $inputString, 'message' => $error->getMessage()]); @@ -59,7 +61,9 @@ class ErrorListener implements EventSubscriberInterface } if (!$inputString = $this->getInputString($event)) { - return $this->logger->debug('The console exited with code "{code}"', ['code' => $exitCode]); + $this->logger->debug('The console exited with code "{code}"', ['code' => $exitCode]); + + return; } $this->logger->debug('Command "{command}" exited with code "{code}"', ['command' => $inputString, 'code' => $exitCode]); diff --git a/lib/symfony/console/Helper/DescriptorHelper.php b/lib/symfony/console/Helper/DescriptorHelper.php index f8a3847b4..3055baefd 100644 --- a/lib/symfony/console/Helper/DescriptorHelper.php +++ b/lib/symfony/console/Helper/DescriptorHelper.php @@ -48,9 +48,7 @@ class DescriptorHelper extends Helper * * format: string, the output format name * * raw_text: boolean, sets output type as raw * - * @param OutputInterface $output - * @param object $object - * @param array $options + * @param object $object * * @throws InvalidArgumentException when the given format is not supported */ @@ -72,8 +70,7 @@ class DescriptorHelper extends Helper /** * Registers a descriptor. * - * @param string $format - * @param DescriptorInterface $descriptor + * @param string $format * * @return $this */ diff --git a/lib/symfony/console/Helper/ProgressIndicator.php b/lib/symfony/console/Helper/ProgressIndicator.php index 3f5751fae..60ca0213b 100644 --- a/lib/symfony/console/Helper/ProgressIndicator.php +++ b/lib/symfony/console/Helper/ProgressIndicator.php @@ -34,10 +34,9 @@ class ProgressIndicator private static $formats; /** - * @param OutputInterface $output - * @param string|null $format Indicator format - * @param int $indicatorChangeInterval Change interval in milliseconds - * @param array|null $indicatorValues Animated indicator characters + * @param string|null $format Indicator format + * @param int $indicatorChangeInterval Change interval in milliseconds + * @param array|null $indicatorValues Animated indicator characters */ public function __construct(OutputInterface $output, $format = null, $indicatorChangeInterval = 100, $indicatorValues = null) { diff --git a/lib/symfony/console/Helper/QuestionHelper.php b/lib/symfony/console/Helper/QuestionHelper.php index 2d910f435..af4d0b9cc 100644 --- a/lib/symfony/console/Helper/QuestionHelper.php +++ b/lib/symfony/console/Helper/QuestionHelper.php @@ -21,6 +21,7 @@ use Symfony\Component\Console\Output\ConsoleOutputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Question\ChoiceQuestion; use Symfony\Component\Console\Question\Question; +use Symfony\Component\Console\Terminal; /** * The QuestionHelper class provides helpers to interact with the user. @@ -157,7 +158,7 @@ class QuestionHelper extends Helper $inputStream = $this->inputStream ?: STDIN; $autocomplete = $question->getAutocompleterValues(); - if (null === $autocomplete || !$this->hasSttyAvailable()) { + if (null === $autocomplete || !Terminal::hasSttyAvailable()) { $ret = false; if ($question->isHidden()) { try { @@ -230,10 +231,7 @@ class QuestionHelper extends Helper /** * Autocompletes a question. * - * @param OutputInterface $output - * @param Question $question - * @param resource $inputStream - * @param array $autocomplete + * @param resource $inputStream * * @return string */ @@ -412,7 +410,7 @@ class QuestionHelper extends Helper return $value; } - if ($this->hasSttyAvailable()) { + if (Terminal::hasSttyAvailable()) { $sttyMode = shell_exec('stty -g'); shell_exec('stty -echo'); @@ -498,20 +496,4 @@ class QuestionHelper extends Helper return self::$shell; } - - /** - * Returns whether Stty is available or not. - * - * @return bool - */ - private function hasSttyAvailable() - { - if (null !== self::$stty) { - return self::$stty; - } - - exec('stty 2>&1', $output, $exitcode); - - return self::$stty = 0 === $exitcode; - } } diff --git a/lib/symfony/console/Helper/Table.php b/lib/symfony/console/Helper/Table.php index 1c439dc1b..0f3d67358 100644 --- a/lib/symfony/console/Helper/Table.php +++ b/lib/symfony/console/Helper/Table.php @@ -193,8 +193,6 @@ class Table /** * Sets the minimum width of all columns. * - * @param array $widths - * * @return $this */ public function setColumnWidths(array $widths) @@ -341,7 +339,6 @@ class Table * * | 9971-5-0210-0 | A Tale of Two Cities | Charles Dickens | * - * @param array $row * @param string $cellFormat */ private function renderRow(array $row, $cellFormat) @@ -361,7 +358,6 @@ class Table /** * Renders table cell with padding. * - * @param array $row * @param int $column * @param string $cellFormat */ @@ -453,8 +449,7 @@ class Table /** * fill rows that contains rowspan > 1. * - * @param array $rows - * @param int $line + * @param int $line * * @return array * @@ -533,8 +528,7 @@ class Table } /** - * @param array $rows - * @param int $line + * @param int $line * * @return array */ @@ -629,8 +623,7 @@ class Table /** * Gets cell width. * - * @param array $row - * @param int $column + * @param int $column * * @return int */ diff --git a/lib/symfony/console/Helper/TableCell.php b/lib/symfony/console/Helper/TableCell.php index cc5145329..78e5d6975 100644 --- a/lib/symfony/console/Helper/TableCell.php +++ b/lib/symfony/console/Helper/TableCell.php @@ -26,7 +26,6 @@ class TableCell /** * @param string $value - * @param array $options */ public function __construct($value = '', array $options = []) { diff --git a/lib/symfony/console/Input/ArgvInput.php b/lib/symfony/console/Input/ArgvInput.php index f604057ec..b0c167d69 100644 --- a/lib/symfony/console/Input/ArgvInput.php +++ b/lib/symfony/console/Input/ArgvInput.php @@ -148,7 +148,7 @@ class ArgvInput extends Input if (false !== $pos = strpos($name, '=')) { if (0 === \strlen($value = substr($name, $pos + 1))) { // if no value after "=" then substr() returns "" since php7 only, false before - // see http://php.net/manual/fr/migration70.incompatible.php#119151 + // see https://php.net/migration70.incompatible.php#119151 if (\PHP_VERSION_ID < 70000 && false === $value) { $value = ''; } @@ -288,6 +288,8 @@ class ArgvInput extends Input return $token; } + + return null; } /** diff --git a/lib/symfony/console/Input/ArrayInput.php b/lib/symfony/console/Input/ArrayInput.php index 44c2f0d5c..a04b6b68e 100644 --- a/lib/symfony/console/Input/ArrayInput.php +++ b/lib/symfony/console/Input/ArrayInput.php @@ -46,6 +46,8 @@ class ArrayInput extends Input return $value; } + + return null; } /** @@ -132,7 +134,7 @@ class ArrayInput extends Input } if (0 === strpos($key, '--')) { $this->addLongOption(substr($key, 2), $value); - } elseif ('-' === $key[0]) { + } elseif (0 === strpos($key, '-')) { $this->addShortOption(substr($key, 1), $value); } else { $this->addArgument($key, $value); diff --git a/lib/symfony/console/Logger/ConsoleLogger.php b/lib/symfony/console/Logger/ConsoleLogger.php index e531bb1ca..6b1745e45 100644 --- a/lib/symfony/console/Logger/ConsoleLogger.php +++ b/lib/symfony/console/Logger/ConsoleLogger.php @@ -22,7 +22,7 @@ use Symfony\Component\Console\Output\OutputInterface; * * @author Kévin Dunglas * - * @see http://www.php-fig.org/psr/psr-3/ + * @see https://www.php-fig.org/psr/psr-3/ */ class ConsoleLogger extends AbstractLogger { @@ -101,7 +101,6 @@ class ConsoleLogger extends AbstractLogger * @author PHP Framework Interoperability Group * * @param string $message - * @param array $context * * @return string */ diff --git a/lib/symfony/console/Question/Question.php b/lib/symfony/console/Question/Question.php index 92b9b6936..06464e135 100644 --- a/lib/symfony/console/Question/Question.php +++ b/lib/symfony/console/Question/Question.php @@ -156,8 +156,6 @@ class Question /** * Sets a validator for the question. * - * @param callable|null $validator - * * @return $this */ public function setValidator(callable $validator = null) @@ -216,8 +214,6 @@ class Question * * The normalizer can be a callable (a string), a closure or a class implementing __invoke. * - * @param callable $normalizer - * * @return $this */ public function setNormalizer(callable $normalizer) @@ -232,7 +228,7 @@ class Question * * The normalizer can ba a callable (a string), a closure or a class implementing __invoke. * - * @return callable + * @return callable|null */ public function getNormalizer() { diff --git a/lib/symfony/console/Style/StyleInterface.php b/lib/symfony/console/Style/StyleInterface.php index 475c268ff..3b5b8af51 100644 --- a/lib/symfony/console/Style/StyleInterface.php +++ b/lib/symfony/console/Style/StyleInterface.php @@ -119,7 +119,6 @@ interface StyleInterface * Asks a choice question. * * @param string $question - * @param array $choices * @param string|int|null $default * * @return mixed diff --git a/lib/symfony/console/Style/SymfonyStyle.php b/lib/symfony/console/Style/SymfonyStyle.php index e0ced01b2..4291ada8f 100644 --- a/lib/symfony/console/Style/SymfonyStyle.php +++ b/lib/symfony/console/Style/SymfonyStyle.php @@ -355,7 +355,9 @@ class SymfonyStyle extends OutputStyle $chars = substr(str_replace(PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2); if (!isset($chars[0])) { - return $this->newLine(); //empty history, so we should start with a new line. + $this->newLine(); //empty history, so we should start with a new line. + + return; } //Prepend new line for each non LF chars (This means no blank line was output before) $this->newLine(2 - substr_count($chars, "\n")); diff --git a/lib/symfony/console/Terminal.php b/lib/symfony/console/Terminal.php index 456cca11c..43a318262 100644 --- a/lib/symfony/console/Terminal.php +++ b/lib/symfony/console/Terminal.php @@ -15,6 +15,7 @@ class Terminal { private static $width; private static $height; + private static $stty; /** * Gets the terminal width. @@ -54,6 +55,22 @@ class Terminal return self::$height ?: 50; } + /** + * @internal + * + * @return bool + */ + public static function hasSttyAvailable() + { + if (null !== self::$stty) { + return self::$stty; + } + + exec('stty 2>&1', $output, $exitcode); + + return self::$stty = 0 === $exitcode; + } + private static function initDimensions() { if ('\\' === \DIRECTORY_SEPARATOR) { @@ -62,12 +79,34 @@ class Terminal // or [w, h] from "wxh" self::$width = (int) $matches[1]; self::$height = isset($matches[4]) ? (int) $matches[4] : (int) $matches[2]; + } elseif (!self::hasVt100Support() && self::hasSttyAvailable()) { + // only use stty on Windows if the terminal does not support vt100 (e.g. Windows 7 + git-bash) + // testing for stty in a Windows 10 vt100-enabled console will implicitly disable vt100 support on STDOUT + self::initDimensionsUsingStty(); } elseif (null !== $dimensions = self::getConsoleMode()) { // extract [w, h] from "wxh" self::$width = (int) $dimensions[0]; self::$height = (int) $dimensions[1]; } - } elseif ($sttyString = self::getSttyColumns()) { + } else { + self::initDimensionsUsingStty(); + } + } + + /** + * Returns whether STDOUT has vt100 support (some Windows 10+ configurations). + */ + private static function hasVt100Support() + { + return \function_exists('sapi_windows_vt100_support') && sapi_windows_vt100_support(fopen('php://stdout', 'w')); + } + + /** + * Initializes dimensions using the output of an stty columns line. + */ + private static function initDimensionsUsingStty() + { + if ($sttyString = self::getSttyColumns()) { if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) { // extract [w, h] from "rows h; columns w;" self::$width = (int) $matches[2]; @@ -87,25 +126,13 @@ class Terminal */ private static function getConsoleMode() { - if (!\function_exists('proc_open')) { - return; + $info = self::readFromProcess('mode CON'); + + if (null === $info || !preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) { + return null; } - $descriptorspec = [ - 1 => ['pipe', 'w'], - 2 => ['pipe', 'w'], - ]; - $process = proc_open('mode CON', $descriptorspec, $pipes, null, null, ['suppress_errors' => true]); - if (\is_resource($process)) { - $info = stream_get_contents($pipes[1]); - fclose($pipes[1]); - fclose($pipes[2]); - proc_close($process); - - if (preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) { - return [(int) $matches[2], (int) $matches[1]]; - } - } + return [(int) $matches[2], (int) $matches[1]]; } /** @@ -114,9 +141,19 @@ class Terminal * @return string|null */ private static function getSttyColumns() + { + return self::readFromProcess('stty -a | grep columns'); + } + + /** + * @param string $command + * + * @return string|null + */ + private static function readFromProcess($command) { if (!\function_exists('proc_open')) { - return; + return null; } $descriptorspec = [ @@ -124,14 +161,16 @@ class Terminal 2 => ['pipe', 'w'], ]; - $process = proc_open('stty -a | grep columns', $descriptorspec, $pipes, null, null, ['suppress_errors' => true]); - if (\is_resource($process)) { - $info = stream_get_contents($pipes[1]); - fclose($pipes[1]); - fclose($pipes[2]); - proc_close($process); - - return $info; + $process = proc_open($command, $descriptorspec, $pipes, null, null, ['suppress_errors' => true]); + if (!\is_resource($process)) { + return null; } + + $info = stream_get_contents($pipes[1]); + fclose($pipes[1]); + fclose($pipes[2]); + proc_close($process); + + return $info; } } diff --git a/lib/symfony/console/Tests/ApplicationTest.php b/lib/symfony/console/Tests/ApplicationTest.php index 181e82593..1ef2ed3d7 100644 --- a/lib/symfony/console/Tests/ApplicationTest.php +++ b/lib/symfony/console/Tests/ApplicationTest.php @@ -74,6 +74,7 @@ class ApplicationTest extends TestCase require_once self::$fixturesPath.'/FooSubnamespaced2Command.php'; require_once self::$fixturesPath.'/TestAmbiguousCommandRegistering.php'; require_once self::$fixturesPath.'/TestAmbiguousCommandRegistering2.php'; + require_once self::$fixturesPath.'/FooHiddenCommand.php'; } protected function normalizeLineBreaks($text) @@ -171,6 +172,7 @@ class ApplicationTest extends TestCase }; $application = new Application(); + $application->setAutoExit(false); $application ->register('test-foo') ->setAliases(['test']) @@ -182,7 +184,7 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); $tester->run(['test']); - $this->assertContains('It works!', $tester->getDisplay(true)); + $this->assertStringContainsString('It works!', $tester->getDisplay(true)); } public function testAdd() @@ -198,12 +200,10 @@ class ApplicationTest extends TestCase $this->assertEquals([$foo, $foo1], [$commands['foo:bar'], $commands['foo:bar1']], '->addCommands() registers an array of commands'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Command class "Foo5Command" is not correctly initialized. You probably forgot to call the parent constructor. - */ public function testAddCommandWithEmptyConstructor() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Command class "Foo5Command" is not correctly initialized. You probably forgot to call the parent constructor.'); $application = new Application(); $application->add(new \Foo5Command()); } @@ -266,12 +266,10 @@ class ApplicationTest extends TestCase $this->assertEmpty($tester->getDisplay(true)); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - * @expectedExceptionMessage The command "foofoo" does not exist. - */ public function testGetInvalidCommand() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); + $this->expectExceptionMessage('The command "foofoo" does not exist.'); $application = new Application(); $application->get('foofoo'); } @@ -311,12 +309,8 @@ class ApplicationTest extends TestCase $expectedMsg = "The namespace \"f\" is ambiguous.\nDid you mean one of these?\n foo\n foo1"; - if (method_exists($this, 'expectException')) { - $this->expectException(CommandNotFoundException::class); - $this->expectExceptionMessage($expectedMsg); - } else { - $this->setExpectedException(CommandNotFoundException::class, $expectedMsg); - } + $this->expectException(CommandNotFoundException::class); + $this->expectExceptionMessage($expectedMsg); $application->findNamespace('f'); } @@ -329,22 +323,18 @@ class ApplicationTest extends TestCase $this->assertEquals('test-ambiguous', $application->find('test')->getName()); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - * @expectedExceptionMessage There are no commands defined in the "bar" namespace. - */ public function testFindInvalidNamespace() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); + $this->expectExceptionMessage('There are no commands defined in the "bar" namespace.'); $application = new Application(); $application->findNamespace('bar'); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - * @expectedExceptionMessage Command "foo1" is not defined - */ public function testFindUniqueNameButNamespaceName() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); + $this->expectExceptionMessage('Command "foo1" is not defined'); $application = new Application(); $application->add(new \FooCommand()); $application->add(new \Foo1Command()); @@ -387,12 +377,10 @@ class ApplicationTest extends TestCase $this->assertInstanceOf('FooSameCaseLowercaseCommand', $application->find('FoO:BaR'), '->find() will fallback to case insensitivity'); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - * @expectedExceptionMessage Command "FoO:BaR" is ambiguous - */ public function testFindCaseInsensitiveSuggestions() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); + $this->expectExceptionMessage('Command "FoO:BaR" is ambiguous'); $application = new Application(); $application->add(new \FooSameCaseLowercaseCommand()); $application->add(new \FooSameCaseUppercaseCommand()); @@ -420,12 +408,8 @@ class ApplicationTest extends TestCase public function testFindWithAmbiguousAbbreviations($abbreviation, $expectedExceptionMessage) { putenv('COLUMNS=120'); - if (method_exists($this, 'expectException')) { - $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); - $this->expectExceptionMessage($expectedExceptionMessage); - } else { - $this->setExpectedException('Symfony\Component\Console\Exception\CommandNotFoundException', $expectedExceptionMessage); - } + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); + $this->expectExceptionMessage($expectedExceptionMessage); $application = new Application(); $application->add(new \FooCommand()); @@ -484,12 +468,12 @@ class ApplicationTest extends TestCase } /** - * @dataProvider provideInvalidCommandNamesSingle - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - * @expectedExceptionMessage Did you mean this + * @dataProvider provideInvalidCommandNamesSingle */ public function testFindAlternativeExceptionMessageSingle($name) { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); + $this->expectExceptionMessage('Did you mean this'); $application = new Application(); $application->add(new \Foo3Command()); $application->find($name); @@ -537,7 +521,7 @@ class ApplicationTest extends TestCase // Subnamespace + plural try { - $a = $application->find('foo3:'); + $application->find('foo3:'); $this->fail('->find() should throw an Symfony\Component\Console\Exception\CommandNotFoundException if a command is ambiguous because of a subnamespace, with alternatives'); } catch (\Exception $e) { $this->assertInstanceOf('Symfony\Component\Console\Exception\CommandNotFoundException', $e); @@ -633,6 +617,7 @@ class ApplicationTest extends TestCase $application->add(new \Foo1Command()); $application->add(new \Foo2Command()); $application->add(new \Foo3Command()); + $application->add(new \FooHiddenCommand()); $expectedAlternatives = [ 'afoobar', @@ -665,12 +650,10 @@ class ApplicationTest extends TestCase $this->assertEquals('foo:sublong', $application->findNamespace('f:sub')); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - * @expectedExceptionMessage Command "foo::bar" is not defined. - */ public function testFindWithDoubleColonInNameThrowsException() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); + $this->expectExceptionMessage('Command "foo::bar" is not defined.'); $application = new Application(); $application->add(new \FooCommand()); $application->add(new \Foo4Command()); @@ -724,7 +707,7 @@ class ApplicationTest extends TestCase $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception1.txt', $tester->getErrorOutput(true), '->renderException() renders a pretty exception'); $tester->run(['command' => 'foo'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE, 'capture_stderr_separately' => true]); - $this->assertContains('Exception trace', $tester->getErrorOutput(), '->renderException() renders a pretty exception with a stack trace when verbosity is verbose'); + $this->assertStringContainsString('Exception trace', $tester->getErrorOutput(), '->renderException() renders a pretty exception with a stack trace when verbosity is verbose'); $tester->run(['command' => 'list', '--foo' => true], ['decorated' => false, 'capture_stderr_separately' => true]); $this->assertStringEqualsFile(self::$fixturesPath.'/application_renderexception2.txt', $tester->getErrorOutput(true), '->renderException() renders the command synopsis when an exception occurs in the context of a command'); @@ -825,7 +808,7 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'foo'], ['decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE]); - $this->assertContains(sprintf('() at %s:', __FILE__), $tester->getDisplay()); + $this->assertStringContainsString(sprintf('() at %s:', __FILE__), $tester->getDisplay()); } public function testRun() @@ -1040,12 +1023,10 @@ class ApplicationTest extends TestCase $this->assertTrue($passedRightValue, '-> exit code 1 was passed in the console.terminate event'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage An option with shortcut "e" already exists. - */ public function testAddingOptionWithDuplicateShortcut() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('An option with shortcut "e" already exists.'); $dispatcher = new EventDispatcher(); $application = new Application(); $application->setAutoExit(false); @@ -1068,11 +1049,11 @@ class ApplicationTest extends TestCase } /** - * @expectedException \LogicException * @dataProvider getAddingAlreadySetDefinitionElementData */ public function testAddingAlreadySetDefinitionElementData($def) { + $this->expectException('LogicException'); $application = new Application(); $application->setAutoExit(false); $application->setCatchExceptions(false); @@ -1221,12 +1202,10 @@ class ApplicationTest extends TestCase $this->assertEquals('before.foo.after.'.PHP_EOL, $tester->getDisplay()); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage error - */ public function testRunWithExceptionAndDispatcher() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('error'); $application = new Application(); $application->setDispatcher($this->getDispatcher()); $application->setAutoExit(false); @@ -1254,7 +1233,7 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'foo']); - $this->assertContains('before.foo.error.after.', $tester->getDisplay()); + $this->assertStringContainsString('before.foo.error.after.', $tester->getDisplay()); } public function testRunDispatchesAllEventsWithExceptionInListener() @@ -1274,7 +1253,7 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'foo']); - $this->assertContains('before.error.after.', $tester->getDisplay()); + $this->assertStringContainsString('before.error.after.', $tester->getDisplay()); } /** @@ -1325,7 +1304,7 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'foo']); - $this->assertContains('before.error.silenced.after.', $tester->getDisplay()); + $this->assertStringContainsString('before.error.silenced.after.', $tester->getDisplay()); $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $tester->getStatusCode()); } @@ -1344,7 +1323,7 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'unknown']); - $this->assertContains('silenced command not found', $tester->getDisplay()); + $this->assertStringContainsString('silenced command not found', $tester->getDisplay()); $this->assertEquals(1, $tester->getStatusCode()); } @@ -1371,8 +1350,8 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'foo']); - $this->assertContains('before.caught.error.after.', $tester->getDisplay()); - $this->assertContains('replaced in caught.', $tester->getDisplay()); + $this->assertStringContainsString('before.caught.error.after.', $tester->getDisplay()); + $this->assertStringContainsString('replaced in caught.', $tester->getDisplay()); } /** @@ -1401,11 +1380,11 @@ class ApplicationTest extends TestCase /** * @requires PHP 7 - * @expectedException \LogicException - * @expectedExceptionMessage error */ public function testRunWithErrorAndDispatcher() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('error'); $application = new Application(); $application->setDispatcher($this->getDispatcher()); $application->setAutoExit(false); @@ -1419,7 +1398,7 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'dym']); - $this->assertContains('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events'); + $this->assertStringContainsString('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events'); } /** @@ -1439,7 +1418,7 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'dym']); - $this->assertContains('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events'); + $this->assertStringContainsString('before.dym.error.after.', $tester->getDisplay(), 'The PHP Error did not dispached events'); } /** @@ -1474,7 +1453,7 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); $exitCode = $tester->run(['command' => 'foo']); - $this->assertContains('before.after.', $tester->getDisplay()); + $this->assertStringContainsString('before.after.', $tester->getDisplay()); $this->assertEquals(ConsoleCommandEvent::RETURN_CODE_DISABLED, $exitCode); } @@ -1602,27 +1581,10 @@ class ApplicationTest extends TestCase $tester = new ApplicationTester($application); $tester->run([]); - $this->assertContains('called', $tester->getDisplay()); + $this->assertStringContainsString('called', $tester->getDisplay()); $tester->run(['--help' => true]); - $this->assertContains('The foo:bar command', $tester->getDisplay()); - } - - /** - * @requires function posix_isatty - */ - public function testCanCheckIfTerminalIsInteractive() - { - $application = new CustomDefaultCommandApplication(); - $application->setAutoExit(false); - - $tester = new ApplicationTester($application); - $tester->run(['command' => 'help']); - - $this->assertFalse($tester->getInput()->hasParameterOption(['--no-interaction', '-n'])); - - $inputStream = $tester->getInput()->getStream(); - $this->assertEquals($tester->getInput()->isInteractive(), @posix_isatty($inputStream)); + $this->assertStringContainsString('The foo:bar command', $tester->getDisplay()); } public function testRunLazyCommandService() @@ -1655,11 +1617,9 @@ class ApplicationTest extends TestCase $this->assertSame(['lazy:alias', 'lazy:alias2'], $command->getAliases()); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - */ public function testGetDisabledLazyCommand() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); $application = new Application(); $application->setCommandLoader(new FactoryCommandLoader(['disabled' => function () { return new DisabledCommand(); }])); $application->get('disabled'); diff --git a/lib/symfony/console/Tests/Command/CommandTest.php b/lib/symfony/console/Tests/Command/CommandTest.php index 9a135d325..207302fdf 100644 --- a/lib/symfony/console/Tests/Command/CommandTest.php +++ b/lib/symfony/console/Tests/Command/CommandTest.php @@ -40,12 +40,10 @@ class CommandTest extends TestCase $this->assertEquals('foo:bar', $command->getName(), '__construct() takes the command name as its first argument'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage The command defined in "Symfony\Component\Console\Command\Command" cannot have an empty name. - */ public function testCommandNameCannotBeEmpty() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('The command defined in "Symfony\Component\Console\Command\Command" cannot have an empty name.'); (new Application())->add(new Command()); } @@ -117,12 +115,8 @@ class CommandTest extends TestCase */ public function testInvalidCommandNames($name) { - if (method_exists($this, 'expectException')) { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage(sprintf('Command name "%s" is invalid.', $name)); - } else { - $this->setExpectedException('InvalidArgumentException', sprintf('Command name "%s" is invalid.', $name)); - } + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage(sprintf('Command name "%s" is invalid.', $name)); $command = new \TestCommand(); $command->setName($name); @@ -160,20 +154,20 @@ class CommandTest extends TestCase { $command = new \TestCommand(); $command->setHelp('The %command.name% command does... Example: php %command.full_name%.'); - $this->assertContains('The namespace:name command does...', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.name% correctly'); - $this->assertNotContains('%command.full_name%', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.full_name%'); + $this->assertStringContainsString('The namespace:name command does...', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.name% correctly'); + $this->assertStringNotContainsString('%command.full_name%', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.full_name%'); $command = new \TestCommand(); $command->setHelp(''); - $this->assertContains('description', $command->getProcessedHelp(), '->getProcessedHelp() falls back to the description'); + $this->assertStringContainsString('description', $command->getProcessedHelp(), '->getProcessedHelp() falls back to the description'); $command = new \TestCommand(); $command->setHelp('The %command.name% command does... Example: php %command.full_name%.'); $application = new Application(); $application->add($command); $application->setDefaultCommand('namespace:name', true); - $this->assertContains('The namespace:name command does...', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.name% correctly in single command applications'); - $this->assertNotContains('%command.full_name%', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.full_name% in single command applications'); + $this->assertStringContainsString('The namespace:name command does...', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.name% correctly in single command applications'); + $this->assertStringNotContainsString('%command.full_name%', $command->getProcessedHelp(), '->getProcessedHelp() replaces %command.full_name% in single command applications'); } public function testGetSetAliases() @@ -188,7 +182,7 @@ class CommandTest extends TestCase public function testSetAliasesNull() { $command = new \TestCommand(); - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException'); + $this->expectException('InvalidArgumentException'); $command->setAliases(null); } @@ -218,12 +212,10 @@ class CommandTest extends TestCase $this->assertEquals($formatterHelper->getName(), $command->getHelper('formatter')->getName(), '->getHelper() returns the correct helper'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Cannot retrieve helper "formatter" because there is no HelperSet defined. - */ public function testGetHelperWithoutHelperSet() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Cannot retrieve helper "formatter" because there is no HelperSet defined.'); $command = new \TestCommand(); $command->getHelper('formatter'); } @@ -291,22 +283,18 @@ class CommandTest extends TestCase $this->assertEquals('execute called'.PHP_EOL, $tester->getDisplay(), '->run() does not call the interact() method if the input is not interactive'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage You must override the execute() method in the concrete command class. - */ public function testExecuteMethodNeedsToBeOverridden() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('You must override the execute() method in the concrete command class.'); $command = new Command('foo'); $command->run(new StringInput(''), new NullOutput()); } - /** - * @expectedException \Symfony\Component\Console\Exception\InvalidOptionException - * @expectedExceptionMessage The "--bar" option does not exist. - */ public function testRunWithInvalidOption() { + $this->expectException('Symfony\Component\Console\Exception\InvalidOptionException'); + $this->expectExceptionMessage('The "--bar" option does not exist.'); $command = new \TestCommand(); $tester = new CommandTester($command); $tester->execute(['--bar' => true]); diff --git a/lib/symfony/console/Tests/Command/HelpCommandTest.php b/lib/symfony/console/Tests/Command/HelpCommandTest.php index ce9d8d4fe..5b25550a6 100644 --- a/lib/symfony/console/Tests/Command/HelpCommandTest.php +++ b/lib/symfony/console/Tests/Command/HelpCommandTest.php @@ -25,9 +25,9 @@ class HelpCommandTest extends TestCase $command->setApplication(new Application()); $commandTester = new CommandTester($command); $commandTester->execute(['command_name' => 'li'], ['decorated' => false]); - $this->assertContains('list [options] [--] []', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias'); - $this->assertContains('format=FORMAT', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias'); - $this->assertContains('raw', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias'); + $this->assertStringContainsString('list [options] [--] []', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias'); + $this->assertStringContainsString('format=FORMAT', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias'); + $this->assertStringContainsString('raw', $commandTester->getDisplay(), '->execute() returns a text help for the given command alias'); } public function testExecuteForCommand() @@ -36,9 +36,9 @@ class HelpCommandTest extends TestCase $commandTester = new CommandTester($command); $command->setCommand(new ListCommand()); $commandTester->execute([], ['decorated' => false]); - $this->assertContains('list [options] [--] []', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); - $this->assertContains('format=FORMAT', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); - $this->assertContains('raw', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); + $this->assertStringContainsString('list [options] [--] []', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); + $this->assertStringContainsString('format=FORMAT', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); + $this->assertStringContainsString('raw', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); } public function testExecuteForCommandWithXmlOption() @@ -47,7 +47,7 @@ class HelpCommandTest extends TestCase $commandTester = new CommandTester($command); $command->setCommand(new ListCommand()); $commandTester->execute(['--format' => 'xml']); - $this->assertContains('getDisplay(), '->execute() returns an XML help text if --xml is passed'); + $this->assertStringContainsString('getDisplay(), '->execute() returns an XML help text if --xml is passed'); } public function testExecuteForApplicationCommand() @@ -55,9 +55,9 @@ class HelpCommandTest extends TestCase $application = new Application(); $commandTester = new CommandTester($application->get('help')); $commandTester->execute(['command_name' => 'list']); - $this->assertContains('list [options] [--] []', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); - $this->assertContains('format=FORMAT', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); - $this->assertContains('raw', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); + $this->assertStringContainsString('list [options] [--] []', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); + $this->assertStringContainsString('format=FORMAT', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); + $this->assertStringContainsString('raw', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); } public function testExecuteForApplicationCommandWithXmlOption() @@ -65,7 +65,7 @@ class HelpCommandTest extends TestCase $application = new Application(); $commandTester = new CommandTester($application->get('help')); $commandTester->execute(['command_name' => 'list', '--format' => 'xml']); - $this->assertContains('list [--raw] [--format FORMAT] [--] [<namespace>]', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); - $this->assertContains('getDisplay(), '->execute() returns an XML help text if --format=xml is passed'); + $this->assertStringContainsString('list [--raw] [--format FORMAT] [--] [<namespace>]', $commandTester->getDisplay(), '->execute() returns a text help for the given command'); + $this->assertStringContainsString('getDisplay(), '->execute() returns an XML help text if --format=xml is passed'); } } diff --git a/lib/symfony/console/Tests/CommandLoader/ContainerCommandLoaderTest.php b/lib/symfony/console/Tests/CommandLoader/ContainerCommandLoaderTest.php index 18d6e77bf..50fe125a6 100644 --- a/lib/symfony/console/Tests/CommandLoader/ContainerCommandLoaderTest.php +++ b/lib/symfony/console/Tests/CommandLoader/ContainerCommandLoaderTest.php @@ -41,11 +41,9 @@ class ContainerCommandLoaderTest extends TestCase $this->assertInstanceOf(Command::class, $loader->get('bar')); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - */ public function testGetUnknownCommandThrows() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); (new ContainerCommandLoader(new ServiceLocator([]), []))->get('unknown'); } diff --git a/lib/symfony/console/Tests/CommandLoader/FactoryCommandLoaderTest.php b/lib/symfony/console/Tests/CommandLoader/FactoryCommandLoaderTest.php index 7b9ec837e..a37ad18de 100644 --- a/lib/symfony/console/Tests/CommandLoader/FactoryCommandLoaderTest.php +++ b/lib/symfony/console/Tests/CommandLoader/FactoryCommandLoaderTest.php @@ -40,11 +40,9 @@ class FactoryCommandLoaderTest extends TestCase $this->assertInstanceOf(Command::class, $loader->get('bar')); } - /** - * @expectedException \Symfony\Component\Console\Exception\CommandNotFoundException - */ public function testGetUnknownCommandThrows() { + $this->expectException('Symfony\Component\Console\Exception\CommandNotFoundException'); (new FactoryCommandLoader([]))->get('unknown'); } diff --git a/lib/symfony/console/Tests/DependencyInjection/AddConsoleCommandPassTest.php b/lib/symfony/console/Tests/DependencyInjection/AddConsoleCommandPassTest.php index b97d0a8f9..1f8ae58e7 100644 --- a/lib/symfony/console/Tests/DependencyInjection/AddConsoleCommandPassTest.php +++ b/lib/symfony/console/Tests/DependencyInjection/AddConsoleCommandPassTest.php @@ -121,12 +121,10 @@ class AddConsoleCommandPassTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The service "my-command" tagged "console.command" must not be abstract. - */ public function testProcessThrowAnExceptionIfTheServiceIsAbstract() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The service "my-command" tagged "console.command" must not be abstract.'); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->addCompilerPass(new AddConsoleCommandPass(), PassConfig::TYPE_BEFORE_REMOVING); @@ -139,12 +137,10 @@ class AddConsoleCommandPassTest extends TestCase $container->compile(); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The service "my-command" tagged "console.command" must be a subclass of "Symfony\Component\Console\Command\Command". - */ public function testProcessThrowAnExceptionIfTheServiceIsNotASubclassOfCommand() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The service "my-command" tagged "console.command" must be a subclass of "Symfony\Component\Console\Command\Command".'); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->addCompilerPass(new AddConsoleCommandPass(), PassConfig::TYPE_BEFORE_REMOVING); @@ -227,12 +223,10 @@ class AddConsoleCommandPassTest extends TestCase $this->assertInstanceOf($className, $command); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage The definition for "my-child-command" has no class. - */ public function testProcessOnChildDefinitionWithoutClass() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('The definition for "my-child-command" has no class.'); $container = new ContainerBuilder(); $container->addCompilerPass(new AddConsoleCommandPass(), PassConfig::TYPE_BEFORE_REMOVING); diff --git a/lib/symfony/console/Tests/Formatter/OutputFormatterStyleStackTest.php b/lib/symfony/console/Tests/Formatter/OutputFormatterStyleStackTest.php index e212bf25e..d3020432e 100644 --- a/lib/symfony/console/Tests/Formatter/OutputFormatterStyleStackTest.php +++ b/lib/symfony/console/Tests/Formatter/OutputFormatterStyleStackTest.php @@ -59,11 +59,9 @@ class OutputFormatterStyleStackTest extends TestCase $this->assertEquals($s1, $stack->pop()); } - /** - * @expectedException \InvalidArgumentException - */ public function testInvalidPop() { + $this->expectException('InvalidArgumentException'); $stack = new OutputFormatterStyleStack(); $stack->push(new OutputFormatterStyle('white', 'black')); $stack->pop(new OutputFormatterStyle('yellow', 'blue')); diff --git a/lib/symfony/console/Tests/Formatter/OutputFormatterStyleTest.php b/lib/symfony/console/Tests/Formatter/OutputFormatterStyleTest.php index d47760fe4..4fe79805c 100644 --- a/lib/symfony/console/Tests/Formatter/OutputFormatterStyleTest.php +++ b/lib/symfony/console/Tests/Formatter/OutputFormatterStyleTest.php @@ -41,7 +41,7 @@ class OutputFormatterStyleTest extends TestCase $style->setForeground('default'); $this->assertEquals("\033[39mfoo\033[39m", $style->apply('foo')); - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException'); + $this->expectException('InvalidArgumentException'); $style->setForeground('undefined-color'); } @@ -58,7 +58,7 @@ class OutputFormatterStyleTest extends TestCase $style->setBackground('default'); $this->assertEquals("\033[49mfoo\033[49m", $style->apply('foo')); - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException'); + $this->expectException('InvalidArgumentException'); $style->setBackground('undefined-color'); } @@ -86,7 +86,7 @@ class OutputFormatterStyleTest extends TestCase $this->fail('->setOption() throws an \InvalidArgumentException when the option does not exist in the available options'); } catch (\Exception $e) { $this->assertInstanceOf('\InvalidArgumentException', $e, '->setOption() throws an \InvalidArgumentException when the option does not exist in the available options'); - $this->assertContains('Invalid option specified: "foo"', $e->getMessage(), '->setOption() throws an \InvalidArgumentException when the option does not exist in the available options'); + $this->assertStringContainsString('Invalid option specified: "foo"', $e->getMessage(), '->setOption() throws an \InvalidArgumentException when the option does not exist in the available options'); } try { @@ -94,7 +94,7 @@ class OutputFormatterStyleTest extends TestCase $this->fail('->unsetOption() throws an \InvalidArgumentException when the option does not exist in the available options'); } catch (\Exception $e) { $this->assertInstanceOf('\InvalidArgumentException', $e, '->unsetOption() throws an \InvalidArgumentException when the option does not exist in the available options'); - $this->assertContains('Invalid option specified: "foo"', $e->getMessage(), '->unsetOption() throws an \InvalidArgumentException when the option does not exist in the available options'); + $this->assertStringContainsString('Invalid option specified: "foo"', $e->getMessage(), '->unsetOption() throws an \InvalidArgumentException when the option does not exist in the available options'); } } } diff --git a/lib/symfony/console/Tests/Helper/HelperSetTest.php b/lib/symfony/console/Tests/Helper/HelperSetTest.php index ffb12b342..d608f7bfd 100644 --- a/lib/symfony/console/Tests/Helper/HelperSetTest.php +++ b/lib/symfony/console/Tests/Helper/HelperSetTest.php @@ -68,7 +68,7 @@ class HelperSetTest extends TestCase } catch (\Exception $e) { $this->assertInstanceOf('\InvalidArgumentException', $e, '->get() throws InvalidArgumentException when helper not found'); $this->assertInstanceOf('Symfony\Component\Console\Exception\ExceptionInterface', $e, '->get() throws domain specific exception when helper not found'); - $this->assertContains('The helper "foo" is not defined.', $e->getMessage(), '->get() throws InvalidArgumentException when helper not found'); + $this->assertStringContainsString('The helper "foo" is not defined.', $e->getMessage(), '->get() throws InvalidArgumentException when helper not found'); } } diff --git a/lib/symfony/console/Tests/Helper/ProgressIndicatorTest.php b/lib/symfony/console/Tests/Helper/ProgressIndicatorTest.php index 6c6f86f36..1428cf5e9 100644 --- a/lib/symfony/console/Tests/Helper/ProgressIndicatorTest.php +++ b/lib/symfony/console/Tests/Helper/ProgressIndicatorTest.php @@ -100,42 +100,34 @@ class ProgressIndicatorTest extends TestCase ); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Must have at least 2 indicator value characters. - */ public function testCannotSetInvalidIndicatorCharacters() { - $bar = new ProgressIndicator($this->getOutputStream(), null, 100, ['1']); + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Must have at least 2 indicator value characters.'); + new ProgressIndicator($this->getOutputStream(), null, 100, ['1']); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Progress indicator already started. - */ public function testCannotStartAlreadyStartedIndicator() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Progress indicator already started.'); $bar = new ProgressIndicator($this->getOutputStream()); $bar->start('Starting...'); $bar->start('Starting Again.'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Progress indicator has not yet been started. - */ public function testCannotAdvanceUnstartedIndicator() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Progress indicator has not yet been started.'); $bar = new ProgressIndicator($this->getOutputStream()); $bar->advance(); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Progress indicator has not yet been started. - */ public function testCannotFinishUnstartedIndicator() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Progress indicator has not yet been started.'); $bar = new ProgressIndicator($this->getOutputStream()); $bar->finish('Finished'); } diff --git a/lib/symfony/console/Tests/Helper/QuestionHelperTest.php b/lib/symfony/console/Tests/Helper/QuestionHelperTest.php index 53819e4be..02cc6ce7e 100644 --- a/lib/symfony/console/Tests/Helper/QuestionHelperTest.php +++ b/lib/symfony/console/Tests/Helper/QuestionHelperTest.php @@ -19,6 +19,7 @@ use Symfony\Component\Console\Output\StreamOutput; use Symfony\Component\Console\Question\ChoiceQuestion; use Symfony\Component\Console\Question\ConfirmationQuestion; use Symfony\Component\Console\Question\Question; +use Symfony\Component\Console\Terminal; /** * @group tty @@ -53,7 +54,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest rewind($output->getStream()); $stream = stream_get_contents($output->getStream()); - $this->assertContains('Input "Fabien" is not a superhero!', $stream); + $this->assertStringContainsString('Input "Fabien" is not a superhero!', $stream); try { $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '1'); @@ -167,7 +168,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest public function testAskWithAutocomplete() { - if (!$this->hasSttyAvailable()) { + if (!Terminal::hasSttyAvailable()) { $this->markTestSkipped('`stty` is required to test autocomplete functionality'); } @@ -200,7 +201,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest public function testAskWithAutocompleteWithNonSequentialKeys() { - if (!$this->hasSttyAvailable()) { + if (!Terminal::hasSttyAvailable()) { $this->markTestSkipped('`stty` is required to test autocomplete functionality'); } @@ -219,7 +220,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest public function testAskWithAutocompleteWithExactMatch() { - if (!$this->hasSttyAvailable()) { + if (!Terminal::hasSttyAvailable()) { $this->markTestSkipped('`stty` is required to test autocomplete functionality'); } @@ -255,7 +256,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest */ public function testAskWithAutocompleteWithMultiByteCharacter($character) { - if (!$this->hasSttyAvailable()) { + if (!Terminal::hasSttyAvailable()) { $this->markTestSkipped('`stty` is required to test autocomplete functionality'); } @@ -279,7 +280,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest public function testAutocompleteWithTrailingBackslash() { - if (!$this->hasSttyAvailable()) { + if (!Terminal::hasSttyAvailable()) { $this->markTestSkipped('`stty` is required to test autocomplete functionality'); } @@ -518,12 +519,10 @@ class QuestionHelperTest extends AbstractQuestionHelperTest $this->assertSame($expectedValue, $answer); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The provided answer is ambiguous. Value should be one of env_2 or env_3. - */ public function testAmbiguousChoiceFromChoicelist() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The provided answer is ambiguous. Value should be one of env_2 or env_3.'); $possibleChoices = [ 'env_1' => 'My first environment', 'env_2' => 'My environment', @@ -618,7 +617,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest rewind($output->getStream()); $stream = stream_get_contents($output->getStream()); - $this->assertContains('Input "Fabien" is not a superhero!', $stream); + $this->assertStringContainsString('Input "Fabien" is not a superhero!', $stream); try { $question = new ChoiceQuestion('What is your favorite superhero?', $heroes, '1'); @@ -674,7 +673,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest */ public function testLegacyAskWithAutocomplete() { - if (!$this->hasSttyAvailable()) { + if (!Terminal::hasSttyAvailable()) { $this->markTestSkipped('`stty` is required to test autocomplete functionality'); } @@ -711,7 +710,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest */ public function testLegacyAskWithAutocompleteWithNonSequentialKeys() { - if (!$this->hasSttyAvailable()) { + if (!Terminal::hasSttyAvailable()) { $this->markTestSkipped('`stty` is required to test autocomplete functionality'); } @@ -748,7 +747,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest } /** - * @group legacy + * @group legacy * @dataProvider getAskConfirmationData */ public function testLegacyAskConfirmation($question, $expected, $default = true) @@ -810,7 +809,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest } /** - * @group legacy + * @group legacy * @dataProvider simpleAnswerProvider */ public function testLegacySelectChoiceFromSimpleChoices($providedAnswer, $expectedValue) @@ -834,7 +833,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest } /** - * @group legacy + * @group legacy * @dataProvider mixedKeysChoiceListAnswerProvider */ public function testLegacyChoiceFromChoicelistWithMixedKeys($providedAnswer, $expectedValue) @@ -859,7 +858,7 @@ class QuestionHelperTest extends AbstractQuestionHelperTest } /** - * @group legacy + * @group legacy * @dataProvider answerProvider */ public function testLegacySelectChoiceFromChoiceList($providedAnswer, $expectedValue) @@ -883,12 +882,12 @@ class QuestionHelperTest extends AbstractQuestionHelperTest } /** - * @group legacy - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The provided answer is ambiguous. Value should be one of env_2 or env_3. + * @group legacy */ public function testLegacyAmbiguousChoiceFromChoicelist() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The provided answer is ambiguous. Value should be one of env_2 or env_3.'); $possibleChoices = [ 'env_1' => 'My first environment', 'env_2' => 'My environment', @@ -938,36 +937,30 @@ class QuestionHelperTest extends AbstractQuestionHelperTest $dialog->ask($this->createInputInterfaceMock(), $output, $question); } - /** - * @expectedException \Symfony\Component\Console\Exception\RuntimeException - * @expectedExceptionMessage Aborted. - */ public function testAskThrowsExceptionOnMissingInput() { + $this->expectException('Symfony\Component\Console\Exception\RuntimeException'); + $this->expectExceptionMessage('Aborted.'); $dialog = new QuestionHelper(); $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?')); } - /** - * @expectedException \Symfony\Component\Console\Exception\RuntimeException - * @expectedExceptionMessage Aborted. - */ public function testAskThrowsExceptionOnMissingInputForChoiceQuestion() { + $this->expectException('Symfony\Component\Console\Exception\RuntimeException'); + $this->expectExceptionMessage('Aborted.'); $dialog = new QuestionHelper(); $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new ChoiceQuestion('Choice', ['a', 'b'])); } - /** - * @expectedException \Symfony\Component\Console\Exception\RuntimeException - * @expectedExceptionMessage Aborted. - */ public function testAskThrowsExceptionOnMissingInputWithValidator() { + $this->expectException('Symfony\Component\Console\Exception\RuntimeException'); + $this->expectExceptionMessage('Aborted.'); $dialog = new QuestionHelper(); $question = new Question('What\'s your name?'); - $question->setValidator(function () { + $question->setValidator(function ($value) { if (!$value) { throw new \Exception('A value is required.'); } @@ -976,18 +969,16 @@ class QuestionHelperTest extends AbstractQuestionHelperTest $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), $question); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Choice question must have at least 1 choice available. - */ public function testEmptyChoices() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Choice question must have at least 1 choice available.'); new ChoiceQuestion('Question', [], 'irrelevant'); } public function testTraversableAutocomplete() { - if (!$this->hasSttyAvailable()) { + if (!Terminal::hasSttyAvailable()) { $this->markTestSkipped('`stty` is required to test autocomplete functionality'); } @@ -1072,13 +1063,6 @@ class QuestionHelperTest extends AbstractQuestionHelperTest return $mock; } - - private function hasSttyAvailable() - { - exec('stty 2>&1', $output, $exitcode); - - return 0 === $exitcode; - } } class AutocompleteValues implements \IteratorAggregate diff --git a/lib/symfony/console/Tests/Helper/SymfonyQuestionHelperTest.php b/lib/symfony/console/Tests/Helper/SymfonyQuestionHelperTest.php index 6f621db95..cbf3b957b 100644 --- a/lib/symfony/console/Tests/Helper/SymfonyQuestionHelperTest.php +++ b/lib/symfony/console/Tests/Helper/SymfonyQuestionHelperTest.php @@ -122,12 +122,10 @@ class SymfonyQuestionHelperTest extends AbstractQuestionHelperTest $this->assertOutputContains('Question with a trailing \\', $output); } - /** - * @expectedException \Symfony\Component\Console\Exception\RuntimeException - * @expectedExceptionMessage Aborted. - */ public function testAskThrowsExceptionOnMissingInput() { + $this->expectException('Symfony\Component\Console\Exception\RuntimeException'); + $this->expectExceptionMessage('Aborted.'); $dialog = new SymfonyQuestionHelper(); $dialog->ask($this->createStreamableInputInterfaceMock($this->getInputStream('')), $this->createOutputInterface(), new Question('What\'s your name?')); } @@ -163,6 +161,6 @@ class SymfonyQuestionHelperTest extends AbstractQuestionHelperTest { rewind($output->getStream()); $stream = stream_get_contents($output->getStream()); - $this->assertContains($expected, $stream); + $this->assertStringContainsString($expected, $stream); } } diff --git a/lib/symfony/console/Tests/Helper/TableStyleTest.php b/lib/symfony/console/Tests/Helper/TableStyleTest.php index 13e918b3a..598019254 100644 --- a/lib/symfony/console/Tests/Helper/TableStyleTest.php +++ b/lib/symfony/console/Tests/Helper/TableStyleTest.php @@ -16,12 +16,10 @@ use Symfony\Component\Console\Helper\TableStyle; class TableStyleTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid padding type. Expected one of (STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH). - */ public function testSetPadTypeWithInvalidType() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Invalid padding type. Expected one of (STR_PAD_LEFT, STR_PAD_RIGHT, STR_PAD_BOTH).'); $style = new TableStyle(); $style->setPadType('TEST'); } diff --git a/lib/symfony/console/Tests/Helper/TableTest.php b/lib/symfony/console/Tests/Helper/TableTest.php index d58a5036d..571cf0a6c 100644 --- a/lib/symfony/console/Tests/Helper/TableTest.php +++ b/lib/symfony/console/Tests/Helper/TableTest.php @@ -726,12 +726,10 @@ TABLE; $this->assertEquals($expected, $this->getOutputContent($output)); } - /** - * @expectedException \Symfony\Component\Console\Exception\InvalidArgumentException - * @expectedExceptionMessage A cell must be a TableCell, a scalar or an object implementing __toString, array given. - */ public function testThrowsWhenTheCellInAnArray() { + $this->expectException('Symfony\Component\Console\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('A cell must be a TableCell, a scalar or an object implementing __toString, array given.'); $table = new Table($output = $this->getOutputStream()); $table ->setHeaders(['ISBN', 'Title', 'Author', 'Price']) @@ -805,22 +803,18 @@ TABLE; $this->assertEquals($expected, $this->getOutputContent($output)); } - /** - * @expectedException \Symfony\Component\Console\Exception\InvalidArgumentException - * @expectedExceptionMessage Style "absent" is not defined. - */ public function testIsNotDefinedStyleException() { + $this->expectException('Symfony\Component\Console\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Style "absent" is not defined.'); $table = new Table($this->getOutputStream()); $table->setStyle('absent'); } - /** - * @expectedException \Symfony\Component\Console\Exception\InvalidArgumentException - * @expectedExceptionMessage Style "absent" is not defined. - */ public function testGetStyleDefinition() { + $this->expectException('Symfony\Component\Console\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Style "absent" is not defined.'); Table::getStyleDefinition('absent'); } diff --git a/lib/symfony/console/Tests/Input/ArgvInputTest.php b/lib/symfony/console/Tests/Input/ArgvInputTest.php index e20bcdd21..51cc6e517 100644 --- a/lib/symfony/console/Tests/Input/ArgvInputTest.php +++ b/lib/symfony/console/Tests/Input/ArgvInputTest.php @@ -182,12 +182,8 @@ class ArgvInputTest extends TestCase */ public function testInvalidInput($argv, $definition, $expectedExceptionMessage) { - if (method_exists($this, 'expectException')) { - $this->expectException('RuntimeException'); - $this->expectExceptionMessage($expectedExceptionMessage); - } else { - $this->setExpectedException('RuntimeException', $expectedExceptionMessage); - } + $this->expectException('RuntimeException'); + $this->expectExceptionMessage($expectedExceptionMessage); $input = new ArgvInput($argv); $input->bind($definition); diff --git a/lib/symfony/console/Tests/Input/ArrayInputTest.php b/lib/symfony/console/Tests/Input/ArrayInputTest.php index afe74831e..5e10223dd 100644 --- a/lib/symfony/console/Tests/Input/ArrayInputTest.php +++ b/lib/symfony/console/Tests/Input/ArrayInputTest.php @@ -127,12 +127,8 @@ class ArrayInputTest extends TestCase */ public function testParseInvalidInput($parameters, $definition, $expectedExceptionMessage) { - if (method_exists($this, 'expectException')) { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage($expectedExceptionMessage); - } else { - $this->setExpectedException('InvalidArgumentException', $expectedExceptionMessage); - } + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage($expectedExceptionMessage); new ArrayInput($parameters, $definition); } diff --git a/lib/symfony/console/Tests/Input/InputArgumentTest.php b/lib/symfony/console/Tests/Input/InputArgumentTest.php index 7561e10ab..1fbcf9fc9 100644 --- a/lib/symfony/console/Tests/Input/InputArgumentTest.php +++ b/lib/symfony/console/Tests/Input/InputArgumentTest.php @@ -42,12 +42,8 @@ class InputArgumentTest extends TestCase */ public function testInvalidModes($mode) { - if (method_exists($this, 'expectException')) { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage(sprintf('Argument mode "%s" is not valid.', $mode)); - } else { - $this->setExpectedException('InvalidArgumentException', sprintf('Argument mode "%s" is not valid.', $mode)); - } + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage(sprintf('Argument mode "%s" is not valid.', $mode)); new InputArgument('foo', $mode); } @@ -95,22 +91,18 @@ class InputArgumentTest extends TestCase $this->assertEquals([1, 2], $argument->getDefault(), '->setDefault() changes the default value'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Cannot set a default value except for InputArgument::OPTIONAL mode. - */ public function testSetDefaultWithRequiredArgument() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Cannot set a default value except for InputArgument::OPTIONAL mode.'); $argument = new InputArgument('foo', InputArgument::REQUIRED); $argument->setDefault('default'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage A default value for an array argument must be an array. - */ public function testSetDefaultWithArrayArgument() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('A default value for an array argument must be an array.'); $argument = new InputArgument('foo', InputArgument::IS_ARRAY); $argument->setDefault('default'); } diff --git a/lib/symfony/console/Tests/Input/InputDefinitionTest.php b/lib/symfony/console/Tests/Input/InputDefinitionTest.php index 5fdcb981c..4a881f595 100644 --- a/lib/symfony/console/Tests/Input/InputDefinitionTest.php +++ b/lib/symfony/console/Tests/Input/InputDefinitionTest.php @@ -20,6 +20,7 @@ class InputDefinitionTest extends TestCase { protected static $fixtures; + protected $multi; protected $foo; protected $bar; protected $foo1; @@ -86,12 +87,10 @@ class InputDefinitionTest extends TestCase $this->assertEquals(['foo' => $this->foo, 'bar' => $this->bar], $definition->getArguments(), '->addArgument() adds a InputArgument object'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage An argument with name "foo" already exists. - */ public function testArgumentsMustHaveDifferentNames() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('An argument with name "foo" already exists.'); $this->initializeArguments(); $definition = new InputDefinition(); @@ -99,12 +98,10 @@ class InputDefinitionTest extends TestCase $definition->addArgument($this->foo1); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Cannot add an argument after an array argument. - */ public function testArrayArgumentHasToBeLast() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Cannot add an argument after an array argument.'); $this->initializeArguments(); $definition = new InputDefinition(); @@ -112,12 +109,10 @@ class InputDefinitionTest extends TestCase $definition->addArgument(new InputArgument('anotherbar')); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Cannot add a required argument after an optional one. - */ public function testRequiredArgumentCannotFollowAnOptionalOne() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Cannot add a required argument after an optional one.'); $this->initializeArguments(); $definition = new InputDefinition(); @@ -134,12 +129,10 @@ class InputDefinitionTest extends TestCase $this->assertEquals($this->foo, $definition->getArgument('foo'), '->getArgument() returns a InputArgument by its name'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "bar" argument does not exist. - */ public function testGetInvalidArgument() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "bar" argument does not exist.'); $this->initializeArguments(); $definition = new InputDefinition(); @@ -206,12 +199,10 @@ class InputDefinitionTest extends TestCase $this->assertEquals(['bar' => $this->bar], $definition->getOptions(), '->setOptions() clears all InputOption objects'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "-f" option does not exist. - */ public function testSetOptionsClearsOptions() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "-f" option does not exist.'); $this->initializeOptions(); $definition = new InputDefinition([$this->foo]); @@ -240,12 +231,10 @@ class InputDefinitionTest extends TestCase $this->assertEquals(['foo' => $this->foo, 'bar' => $this->bar], $definition->getOptions(), '->addOption() adds a InputOption object'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage An option named "foo" already exists. - */ public function testAddDuplicateOption() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('An option named "foo" already exists.'); $this->initializeOptions(); $definition = new InputDefinition(); @@ -253,12 +242,10 @@ class InputDefinitionTest extends TestCase $definition->addOption($this->foo2); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage An option with shortcut "f" already exists. - */ public function testAddDuplicateShortcutOption() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('An option with shortcut "f" already exists.'); $this->initializeOptions(); $definition = new InputDefinition(); @@ -274,12 +261,10 @@ class InputDefinitionTest extends TestCase $this->assertEquals($this->foo, $definition->getOption('foo'), '->getOption() returns a InputOption by its name'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "--bar" option does not exist. - */ public function testGetInvalidOption() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "--bar" option does not exist.'); $this->initializeOptions(); $definition = new InputDefinition([$this->foo]); @@ -321,12 +306,10 @@ class InputDefinitionTest extends TestCase $this->assertEquals($this->multi, $definition->getOptionForShortcut('mmm'), '->getOptionForShortcut() returns a InputOption by its shortcut'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "-l" option does not exist. - */ public function testGetOptionForInvalidShortcut() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "-l" option does not exist.'); $this->initializeOptions(); $definition = new InputDefinition([$this->foo]); diff --git a/lib/symfony/console/Tests/Input/InputOptionTest.php b/lib/symfony/console/Tests/Input/InputOptionTest.php index 413cb5270..f7dcbd18f 100644 --- a/lib/symfony/console/Tests/Input/InputOptionTest.php +++ b/lib/symfony/console/Tests/Input/InputOptionTest.php @@ -24,12 +24,10 @@ class InputOptionTest extends TestCase $this->assertEquals('foo', $option->getName(), '__construct() removes the leading -- of the option name'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value. - */ public function testArrayModeWithoutValue() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.'); new InputOption('foo', 'f', InputOption::VALUE_IS_ARRAY); } @@ -78,12 +76,8 @@ class InputOptionTest extends TestCase */ public function testInvalidModes($mode) { - if (method_exists($this, 'expectException')) { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage(sprintf('Option mode "%s" is not valid.', $mode)); - } else { - $this->setExpectedException('InvalidArgumentException', sprintf('Option mode "%s" is not valid.', $mode)); - } + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage(sprintf('Option mode "%s" is not valid.', $mode)); new InputOption('foo', 'f', $mode); } @@ -96,27 +90,21 @@ class InputOptionTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - */ public function testEmptyNameIsInvalid() { + $this->expectException('InvalidArgumentException'); new InputOption(''); } - /** - * @expectedException \InvalidArgumentException - */ public function testDoubleDashNameIsInvalid() { + $this->expectException('InvalidArgumentException'); new InputOption('--'); } - /** - * @expectedException \InvalidArgumentException - */ public function testSingleDashOptionIsInvalid() { + $this->expectException('InvalidArgumentException'); new InputOption('foo', '-'); } @@ -165,22 +153,18 @@ class InputOptionTest extends TestCase $this->assertEquals([1, 2], $option->getDefault(), '->setDefault() changes the default value'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Cannot set a default value when using InputOption::VALUE_NONE mode. - */ public function testDefaultValueWithValueNoneMode() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Cannot set a default value when using InputOption::VALUE_NONE mode.'); $option = new InputOption('foo', 'f', InputOption::VALUE_NONE); $option->setDefault('default'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage A default value for an array option must be an array. - */ public function testDefaultValueWithIsArrayMode() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('A default value for an array option must be an array.'); $option = new InputOption('foo', 'f', InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY); $option->setDefault('default'); } diff --git a/lib/symfony/console/Tests/Input/InputTest.php b/lib/symfony/console/Tests/Input/InputTest.php index 61608bf27..060b750f4 100644 --- a/lib/symfony/console/Tests/Input/InputTest.php +++ b/lib/symfony/console/Tests/Input/InputTest.php @@ -47,22 +47,18 @@ class InputTest extends TestCase $this->assertEquals(['name' => 'foo', 'bar' => null], $input->getOptions(), '->getOptions() returns all option values'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "foo" option does not exist. - */ public function testSetInvalidOption() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "foo" option does not exist.'); $input = new ArrayInput(['--name' => 'foo'], new InputDefinition([new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default')])); $input->setOption('foo', 'bar'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "foo" option does not exist. - */ public function testGetInvalidOption() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "foo" option does not exist.'); $input = new ArrayInput(['--name' => 'foo'], new InputDefinition([new InputOption('name'), new InputOption('bar', '', InputOption::VALUE_OPTIONAL, '', 'default')])); $input->getOption('foo'); } @@ -81,43 +77,35 @@ class InputTest extends TestCase $this->assertEquals(['name' => 'foo', 'bar' => 'default'], $input->getArguments(), '->getArguments() returns all argument values, even optional ones'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "foo" argument does not exist. - */ public function testSetInvalidArgument() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "foo" argument does not exist.'); $input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default')])); $input->setArgument('foo', 'bar'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The "foo" argument does not exist. - */ public function testGetInvalidArgument() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "foo" argument does not exist.'); $input = new ArrayInput(['name' => 'foo'], new InputDefinition([new InputArgument('name'), new InputArgument('bar', InputArgument::OPTIONAL, '', 'default')])); $input->getArgument('foo'); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Not enough arguments (missing: "name"). - */ public function testValidateWithMissingArguments() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Not enough arguments (missing: "name").'); $input = new ArrayInput([]); $input->bind(new InputDefinition([new InputArgument('name', InputArgument::REQUIRED)])); $input->validate(); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Not enough arguments (missing: "name"). - */ public function testValidateWithMissingRequiredArguments() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Not enough arguments (missing: "name").'); $input = new ArrayInput(['bar' => 'baz']); $input->bind(new InputDefinition([new InputArgument('name', InputArgument::REQUIRED), new InputArgument('bar', InputArgument::OPTIONAL)])); $input->validate(); diff --git a/lib/symfony/console/Tests/Logger/ConsoleLoggerTest.php b/lib/symfony/console/Tests/Logger/ConsoleLoggerTest.php index c99eb839b..f1bbb61c5 100644 --- a/lib/symfony/console/Tests/Logger/ConsoleLoggerTest.php +++ b/lib/symfony/console/Tests/Logger/ConsoleLoggerTest.php @@ -141,11 +141,9 @@ class ConsoleLoggerTest extends TestCase ]; } - /** - * @expectedException \Psr\Log\InvalidArgumentException - */ public function testThrowsOnInvalidLevel() { + $this->expectException('Psr\Log\InvalidArgumentException'); $logger = $this->getLogger(); $logger->log('invalid level', 'Foo'); } @@ -164,7 +162,7 @@ class ConsoleLoggerTest extends TestCase if (method_exists($this, 'createPartialMock')) { $dummy = $this->createPartialMock('Symfony\Component\Console\Tests\Logger\DummyTest', ['__toString']); } else { - $dummy = $this->getMock('Symfony\Component\Console\Tests\Logger\DummyTest', ['__toString']); + $dummy = $this->createPartialMock('Symfony\Component\Console\Tests\Logger\DummyTest', ['__toString']); } $dummy->method('__toString')->willReturn('DUMMY'); diff --git a/lib/symfony/console/Tests/Output/StreamOutputTest.php b/lib/symfony/console/Tests/Output/StreamOutputTest.php index 780b5681f..d843fa4a4 100644 --- a/lib/symfony/console/Tests/Output/StreamOutputTest.php +++ b/lib/symfony/console/Tests/Output/StreamOutputTest.php @@ -36,12 +36,10 @@ class StreamOutputTest extends TestCase $this->assertTrue($output->isDecorated(), '__construct() takes the decorated flag as its second argument'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The StreamOutput class needs a stream as its first argument. - */ public function testStreamIsRequired() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The StreamOutput class needs a stream as its first argument.'); new StreamOutput('foo'); } diff --git a/lib/symfony/console/Tests/TerminalTest.php b/lib/symfony/console/Tests/TerminalTest.php index 93b8c44a7..546d2214c 100644 --- a/lib/symfony/console/Tests/TerminalTest.php +++ b/lib/symfony/console/Tests/TerminalTest.php @@ -18,17 +18,31 @@ class TerminalTest extends TestCase { private $colSize; private $lineSize; + private $ansiCon; protected function setUp() { $this->colSize = getenv('COLUMNS'); $this->lineSize = getenv('LINES'); + $this->ansiCon = getenv('ANSICON'); + $this->resetStatics(); } protected function tearDown() { putenv($this->colSize ? 'COLUMNS='.$this->colSize : 'COLUMNS'); putenv($this->lineSize ? 'LINES' : 'LINES='.$this->lineSize); + putenv($this->ansiCon ? 'ANSICON='.$this->ansiCon : 'ANSICON'); + $this->resetStatics(); + } + + private function resetStatics() + { + foreach (['height', 'width', 'stty'] as $name) { + $property = new \ReflectionProperty(Terminal::class, $name); + $property->setAccessible(true); + $property->setValue(null); + } } public function test() @@ -56,4 +70,28 @@ class TerminalTest extends TestCase $this->assertSame(0, $terminal->getWidth()); $this->assertSame(0, $terminal->getHeight()); } + + public function testSttyOnWindows() + { + if ('\\' !== \DIRECTORY_SEPARATOR) { + $this->markTestSkipped('Must be on windows'); + } + + $sttyString = exec('(stty -a | grep columns) 2>&1', $output, $exitcode); + if (0 !== $exitcode) { + $this->markTestSkipped('Must have stty support'); + } + + $matches = []; + if (0 === preg_match('/columns.(\d+)/i', $sttyString, $matches)) { + $this->fail('Could not determine existing stty columns'); + } + + putenv('COLUMNS'); + putenv('LINES'); + putenv('ANSICON'); + + $terminal = new Terminal(); + $this->assertSame((int) $matches[1], $terminal->getWidth()); + } } diff --git a/lib/symfony/console/Tests/Tester/CommandTesterTest.php b/lib/symfony/console/Tests/Tester/CommandTesterTest.php index f916b1821..1fa829236 100644 --- a/lib/symfony/console/Tests/Tester/CommandTesterTest.php +++ b/lib/symfony/console/Tests/Tester/CommandTesterTest.php @@ -138,12 +138,10 @@ class CommandTesterTest extends TestCase $this->assertEquals(implode('', $questions), $tester->getDisplay(true)); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Aborted. - */ public function testCommandWithWrongInputsNumber() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Aborted.'); $questions = [ 'What\'s your name?', 'How are you?', @@ -165,12 +163,10 @@ class CommandTesterTest extends TestCase $tester->execute([]); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Aborted. - */ public function testCommandWithQuestionsButNoInputs() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Aborted.'); $questions = [ 'What\'s your name?', 'How are you?', @@ -200,7 +196,7 @@ class CommandTesterTest extends TestCase ]; $command = new Command('foo'); - $command->setCode(function ($input, $output) use ($questions, $command) { + $command->setCode(function ($input, $output) use ($questions) { $io = new SymfonyStyle($input, $output); $io->ask($questions[0]); $io->ask($questions[1]); diff --git a/lib/symfony/css-selector/Exception/SyntaxErrorException.php b/lib/symfony/css-selector/Exception/SyntaxErrorException.php index cb3158a55..1200c979e 100644 --- a/lib/symfony/css-selector/Exception/SyntaxErrorException.php +++ b/lib/symfony/css-selector/Exception/SyntaxErrorException.php @@ -25,7 +25,6 @@ class SyntaxErrorException extends ParseException { /** * @param string $expectedValue - * @param Token $foundToken * * @return self */ diff --git a/lib/symfony/css-selector/Node/AttributeNode.php b/lib/symfony/css-selector/Node/AttributeNode.php index 1caccb6bf..c09d92477 100644 --- a/lib/symfony/css-selector/Node/AttributeNode.php +++ b/lib/symfony/css-selector/Node/AttributeNode.php @@ -30,11 +30,10 @@ class AttributeNode extends AbstractNode private $value; /** - * @param NodeInterface $selector - * @param string $namespace - * @param string $attribute - * @param string $operator - * @param string $value + * @param string $namespace + * @param string $attribute + * @param string $operator + * @param string $value */ public function __construct(NodeInterface $selector, $namespace, $attribute, $operator, $value) { diff --git a/lib/symfony/css-selector/Node/ClassNode.php b/lib/symfony/css-selector/Node/ClassNode.php index 69462e8e7..866607cba 100644 --- a/lib/symfony/css-selector/Node/ClassNode.php +++ b/lib/symfony/css-selector/Node/ClassNode.php @@ -27,8 +27,7 @@ class ClassNode extends AbstractNode private $name; /** - * @param NodeInterface $selector - * @param string $name + * @param string $name */ public function __construct(NodeInterface $selector, $name) { diff --git a/lib/symfony/css-selector/Node/CombinedSelectorNode.php b/lib/symfony/css-selector/Node/CombinedSelectorNode.php index 2aa583aaf..27b022485 100644 --- a/lib/symfony/css-selector/Node/CombinedSelectorNode.php +++ b/lib/symfony/css-selector/Node/CombinedSelectorNode.php @@ -28,9 +28,7 @@ class CombinedSelectorNode extends AbstractNode private $subSelector; /** - * @param NodeInterface $selector - * @param string $combinator - * @param NodeInterface $subSelector + * @param string $combinator */ public function __construct(NodeInterface $selector, $combinator, NodeInterface $subSelector) { diff --git a/lib/symfony/css-selector/Node/FunctionNode.php b/lib/symfony/css-selector/Node/FunctionNode.php index 677affaa9..b6f95e975 100644 --- a/lib/symfony/css-selector/Node/FunctionNode.php +++ b/lib/symfony/css-selector/Node/FunctionNode.php @@ -30,9 +30,8 @@ class FunctionNode extends AbstractNode private $arguments; /** - * @param NodeInterface $selector - * @param string $name - * @param Token[] $arguments + * @param string $name + * @param Token[] $arguments */ public function __construct(NodeInterface $selector, $name, array $arguments = []) { diff --git a/lib/symfony/css-selector/Node/HashNode.php b/lib/symfony/css-selector/Node/HashNode.php index ebf9a9872..3ea89dc18 100644 --- a/lib/symfony/css-selector/Node/HashNode.php +++ b/lib/symfony/css-selector/Node/HashNode.php @@ -27,8 +27,7 @@ class HashNode extends AbstractNode private $id; /** - * @param NodeInterface $selector - * @param string $id + * @param string $id */ public function __construct(NodeInterface $selector, $id) { diff --git a/lib/symfony/css-selector/Node/PseudoNode.php b/lib/symfony/css-selector/Node/PseudoNode.php index 3842c695e..c7d0b9fb3 100644 --- a/lib/symfony/css-selector/Node/PseudoNode.php +++ b/lib/symfony/css-selector/Node/PseudoNode.php @@ -27,8 +27,7 @@ class PseudoNode extends AbstractNode private $identifier; /** - * @param NodeInterface $selector - * @param string $identifier + * @param string $identifier */ public function __construct(NodeInterface $selector, $identifier) { diff --git a/lib/symfony/css-selector/Node/SelectorNode.php b/lib/symfony/css-selector/Node/SelectorNode.php index 057107f6f..2379babff 100644 --- a/lib/symfony/css-selector/Node/SelectorNode.php +++ b/lib/symfony/css-selector/Node/SelectorNode.php @@ -27,8 +27,7 @@ class SelectorNode extends AbstractNode private $pseudoElement; /** - * @param NodeInterface $tree - * @param string|null $pseudoElement + * @param string|null $pseudoElement */ public function __construct(NodeInterface $tree, $pseudoElement = null) { diff --git a/lib/symfony/css-selector/Parser/Parser.php b/lib/symfony/css-selector/Parser/Parser.php index f07985ac5..7b131efdb 100644 --- a/lib/symfony/css-selector/Parser/Parser.php +++ b/lib/symfony/css-selector/Parser/Parser.php @@ -158,8 +158,7 @@ class Parser implements ParserInterface /** * Parses next simple node (hash, class, pseudo, negation). * - * @param TokenStream $stream - * @param bool $insideNegation + * @param bool $insideNegation * * @return array * diff --git a/lib/symfony/css-selector/Parser/TokenStream.php b/lib/symfony/css-selector/Parser/TokenStream.php index 843e330b5..001bfe1a7 100644 --- a/lib/symfony/css-selector/Parser/TokenStream.php +++ b/lib/symfony/css-selector/Parser/TokenStream.php @@ -155,7 +155,7 @@ class TokenStream } if ($next->isDelimiter(['*'])) { - return; + return null; } throw SyntaxErrorException::unexpectedToken('identifier or "*"', $next); diff --git a/lib/symfony/css-selector/Parser/Tokenizer/TokenizerEscaping.php b/lib/symfony/css-selector/Parser/Tokenizer/TokenizerEscaping.php index 55ea42149..ce322e96f 100644 --- a/lib/symfony/css-selector/Parser/Tokenizer/TokenizerEscaping.php +++ b/lib/symfony/css-selector/Parser/Tokenizer/TokenizerEscaping.php @@ -73,6 +73,8 @@ class TokenizerEscaping if (0x10000 > $c) { return \chr(0xE0 | $c >> 12).\chr(0x80 | $c >> 6 & 0x3F).\chr(0x80 | $c & 0x3F); } + + return ''; }, $value); } } diff --git a/lib/symfony/css-selector/Tests/CssSelectorConverterTest.php b/lib/symfony/css-selector/Tests/CssSelectorConverterTest.php index cd0fd785e..82e527c62 100644 --- a/lib/symfony/css-selector/Tests/CssSelectorConverterTest.php +++ b/lib/symfony/css-selector/Tests/CssSelectorConverterTest.php @@ -35,12 +35,10 @@ class CssSelectorConverterTest extends TestCase $this->assertEquals('descendant-or-self::H1', $converter->toXPath('H1')); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ParseException - * @expectedExceptionMessage Expected identifier, but found. - */ public function testParseExceptions() { + $this->expectException('Symfony\Component\CssSelector\Exception\ParseException'); + $this->expectExceptionMessage('Expected identifier, but found.'); $converter = new CssSelectorConverter(); $converter->toXPath('h1:'); } diff --git a/lib/symfony/css-selector/Tests/Parser/ParserTest.php b/lib/symfony/css-selector/Tests/Parser/ParserTest.php index de3509348..f63a15e0a 100644 --- a/lib/symfony/css-selector/Tests/Parser/ParserTest.php +++ b/lib/symfony/css-selector/Tests/Parser/ParserTest.php @@ -89,7 +89,7 @@ class ParserTest extends TestCase /** @var FunctionNode $function */ $function = $selectors[0]->getTree(); - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\CssSelector\Exception\SyntaxErrorException'); + $this->expectException('Symfony\Component\CssSelector\Exception\SyntaxErrorException'); Parser::parseSeries($function->getArguments()); } diff --git a/lib/symfony/css-selector/Tests/Parser/TokenStreamTest.php b/lib/symfony/css-selector/Tests/Parser/TokenStreamTest.php index 44c751ac8..fb47625a8 100644 --- a/lib/symfony/css-selector/Tests/Parser/TokenStreamTest.php +++ b/lib/symfony/css-selector/Tests/Parser/TokenStreamTest.php @@ -53,7 +53,7 @@ class TokenStreamTest extends TestCase public function testFailToGetNextIdentifier() { - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\CssSelector\Exception\SyntaxErrorException'); + $this->expectException('Symfony\Component\CssSelector\Exception\SyntaxErrorException'); $stream = new TokenStream(); $stream->push(new Token(Token::TYPE_DELIMITER, '.', 2)); @@ -73,7 +73,7 @@ class TokenStreamTest extends TestCase public function testFailToGetNextIdentifierOrStar() { - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\CssSelector\Exception\SyntaxErrorException'); + $this->expectException('Symfony\Component\CssSelector\Exception\SyntaxErrorException'); $stream = new TokenStream(); $stream->push(new Token(Token::TYPE_DELIMITER, '.', 2)); diff --git a/lib/symfony/css-selector/Tests/XPath/TranslatorTest.php b/lib/symfony/css-selector/Tests/XPath/TranslatorTest.php index a9ab29e2a..a718fbd6f 100644 --- a/lib/symfony/css-selector/Tests/XPath/TranslatorTest.php +++ b/lib/symfony/css-selector/Tests/XPath/TranslatorTest.php @@ -35,31 +35,25 @@ class TranslatorTest extends TestCase $this->assertEquals($xpath, $translator->cssToXPath($css, '')); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ExpressionErrorException - */ public function testCssToXPathPseudoElement() { + $this->expectException('Symfony\Component\CssSelector\Exception\ExpressionErrorException'); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $translator->cssToXPath('e::first-line'); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ExpressionErrorException - */ public function testGetExtensionNotExistsExtension() { + $this->expectException('Symfony\Component\CssSelector\Exception\ExpressionErrorException'); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $translator->getExtension('fake'); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ExpressionErrorException - */ public function testAddCombinationNotExistsExtension() { + $this->expectException('Symfony\Component\CssSelector\Exception\ExpressionErrorException'); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $parser = new Parser(); @@ -68,11 +62,9 @@ class TranslatorTest extends TestCase $translator->addCombination('fake', $xpath, $combinedXpath); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ExpressionErrorException - */ public function testAddFunctionNotExistsFunction() { + $this->expectException('Symfony\Component\CssSelector\Exception\ExpressionErrorException'); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $xpath = new XPathExpr(); @@ -80,22 +72,18 @@ class TranslatorTest extends TestCase $translator->addFunction($xpath, $function); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ExpressionErrorException - */ public function testAddPseudoClassNotExistsClass() { + $this->expectException('Symfony\Component\CssSelector\Exception\ExpressionErrorException'); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $xpath = new XPathExpr(); $translator->addPseudoClass($xpath, 'fake'); } - /** - * @expectedException \Symfony\Component\CssSelector\Exception\ExpressionErrorException - */ public function testAddAttributeMatchingClassNotExistsClass() { + $this->expectException('Symfony\Component\CssSelector\Exception\ExpressionErrorException'); $translator = new Translator(); $translator->registerExtension(new HtmlExtension($translator)); $xpath = new XPathExpr(); @@ -110,7 +98,7 @@ class TranslatorTest extends TestCase $elements = $document->xpath($translator->cssToXPath($css)); $this->assertCount(\count($elementsId), $elements); foreach ($elements as $element) { - $this->assertTrue(\in_array($element->attributes()->id, $elementsId)); + $this->assertContains((string) $element->attributes()->id, $elementsId); } } @@ -128,7 +116,7 @@ class TranslatorTest extends TestCase $this->assertCount(\count($elementsId), $elementsId); foreach ($elements as $element) { if (null !== $element->attributes()->id) { - $this->assertTrue(\in_array($element->attributes()->id, $elementsId)); + $this->assertContains((string) $element->attributes()->id, $elementsId); } } libxml_clear_errors(); @@ -149,6 +137,33 @@ class TranslatorTest extends TestCase $this->assertCount($count, $elements); } + public function testOnlyOfTypeFindsSingleChildrenOfGivenType() + { + $translator = new Translator(); + $translator->registerExtension(new HtmlExtension($translator)); + $document = new \DOMDocument(); + $document->loadHTML(<<<'HTML' + + +

+ A +

+

+ B + C +

+ + +HTML +); + + $xpath = new \DOMXPath($document); + $nodeList = $xpath->query($translator->cssToXPath('span:only-of-type')); + + $this->assertSame(1, $nodeList->length); + $this->assertSame('A', $nodeList->item(0)->textContent); + } + public function getXpathLiteralTestData() { return [ @@ -187,7 +202,7 @@ class TranslatorTest extends TestCase ['e:first-of-type', '*/e[position() = 1]'], ['e:last-of-type', '*/e[position() = last()]'], ['e:only-child', "*/*[(name() = 'e') and (last() = 1)]"], - ['e:only-of-type', 'e[last() = 1]'], + ['e:only-of-type', 'e[count(preceding-sibling::e)=0 and count(following-sibling::e)=0]'], ['e:empty', 'e[not(*) and not(string-length())]'], ['e:EmPTY', 'e[not(*) and not(string-length())]'], ['e:root', 'e[not(parent::*)]'], diff --git a/lib/symfony/css-selector/XPath/Extension/AttributeMatchingExtension.php b/lib/symfony/css-selector/XPath/Extension/AttributeMatchingExtension.php index 0571b3b76..f27878b14 100644 --- a/lib/symfony/css-selector/XPath/Extension/AttributeMatchingExtension.php +++ b/lib/symfony/css-selector/XPath/Extension/AttributeMatchingExtension.php @@ -44,9 +44,8 @@ class AttributeMatchingExtension extends AbstractExtension } /** - * @param XPathExpr $xpath - * @param string $attribute - * @param string $value + * @param string $attribute + * @param string $value * * @return XPathExpr */ @@ -56,9 +55,8 @@ class AttributeMatchingExtension extends AbstractExtension } /** - * @param XPathExpr $xpath - * @param string $attribute - * @param string $value + * @param string $attribute + * @param string $value * * @return XPathExpr */ @@ -68,9 +66,8 @@ class AttributeMatchingExtension extends AbstractExtension } /** - * @param XPathExpr $xpath - * @param string $attribute - * @param string $value + * @param string $attribute + * @param string $value * * @return XPathExpr */ @@ -84,9 +81,8 @@ class AttributeMatchingExtension extends AbstractExtension } /** - * @param XPathExpr $xpath - * @param string $attribute - * @param string $value + * @param string $attribute + * @param string $value * * @return XPathExpr */ @@ -101,9 +97,8 @@ class AttributeMatchingExtension extends AbstractExtension } /** - * @param XPathExpr $xpath - * @param string $attribute - * @param string $value + * @param string $attribute + * @param string $value * * @return XPathExpr */ @@ -117,9 +112,8 @@ class AttributeMatchingExtension extends AbstractExtension } /** - * @param XPathExpr $xpath - * @param string $attribute - * @param string $value + * @param string $attribute + * @param string $value * * @return XPathExpr */ @@ -134,9 +128,8 @@ class AttributeMatchingExtension extends AbstractExtension } /** - * @param XPathExpr $xpath - * @param string $attribute - * @param string $value + * @param string $attribute + * @param string $value * * @return XPathExpr */ @@ -150,9 +143,8 @@ class AttributeMatchingExtension extends AbstractExtension } /** - * @param XPathExpr $xpath - * @param string $attribute - * @param string $value + * @param string $attribute + * @param string $value * * @return XPathExpr */ diff --git a/lib/symfony/css-selector/XPath/Extension/FunctionExtension.php b/lib/symfony/css-selector/XPath/Extension/FunctionExtension.php index a8e0b69f1..2b8aa6a19 100644 --- a/lib/symfony/css-selector/XPath/Extension/FunctionExtension.php +++ b/lib/symfony/css-selector/XPath/Extension/FunctionExtension.php @@ -46,10 +46,8 @@ class FunctionExtension extends AbstractExtension } /** - * @param XPathExpr $xpath - * @param FunctionNode $function - * @param bool $last - * @param bool $addNameTest + * @param bool $last + * @param bool $addNameTest * * @return XPathExpr * diff --git a/lib/symfony/css-selector/XPath/Extension/PseudoClassExtension.php b/lib/symfony/css-selector/XPath/Extension/PseudoClassExtension.php index 27fe47f9a..288a9e695 100644 --- a/lib/symfony/css-selector/XPath/Extension/PseudoClassExtension.php +++ b/lib/symfony/css-selector/XPath/Extension/PseudoClassExtension.php @@ -123,11 +123,13 @@ class PseudoClassExtension extends AbstractExtension */ public function translateOnlyOfType(XPathExpr $xpath) { - if ('*' === $xpath->getElement()) { + $element = $xpath->getElement(); + + if ('*' === $element) { throw new ExpressionErrorException('"*:only-of-type" is not implemented.'); } - return $xpath->addCondition('last() = 1'); + return $xpath->addCondition(sprintf('count(preceding-sibling::%s)=0 and count(following-sibling::%s)=0', $element, $element)); } /** diff --git a/lib/symfony/css-selector/XPath/Translator.php b/lib/symfony/css-selector/XPath/Translator.php index d07812677..738886031 100644 --- a/lib/symfony/css-selector/XPath/Translator.php +++ b/lib/symfony/css-selector/XPath/Translator.php @@ -180,9 +180,7 @@ class Translator implements TranslatorInterface } /** - * @param string $combiner - * @param NodeInterface $xpath - * @param NodeInterface $combinedXpath + * @param string $combiner * * @return XPathExpr * @@ -212,8 +210,7 @@ class Translator implements TranslatorInterface } /** - * @param XPathExpr $xpath - * @param string $pseudoClass + * @param string $pseudoClass * * @return XPathExpr * @@ -229,10 +226,9 @@ class Translator implements TranslatorInterface } /** - * @param XPathExpr $xpath - * @param string $operator - * @param string $attribute - * @param string $value + * @param string $operator + * @param string $attribute + * @param string $value * * @return XPathExpr * diff --git a/lib/symfony/css-selector/XPath/TranslatorInterface.php b/lib/symfony/css-selector/XPath/TranslatorInterface.php index 0b5de83d5..fdbdf2255 100644 --- a/lib/symfony/css-selector/XPath/TranslatorInterface.php +++ b/lib/symfony/css-selector/XPath/TranslatorInterface.php @@ -38,8 +38,7 @@ interface TranslatorInterface /** * Translates a parsed selector node to an XPath expression. * - * @param SelectorNode $selector - * @param string $prefix + * @param string $prefix * * @return string */ diff --git a/lib/symfony/debug/DebugClassLoader.php b/lib/symfony/debug/DebugClassLoader.php index 13ab9e700..b0174187a 100644 --- a/lib/symfony/debug/DebugClassLoader.php +++ b/lib/symfony/debug/DebugClassLoader.php @@ -317,6 +317,12 @@ class DebugClassLoader return $deprecations; } + /** + * @param string $file + * @param string $class + * + * @return array|null + */ public function checkCase(\ReflectionClass $refl, $file, $class) { $real = explode('\\', $class.strrchr($file, '.')); @@ -333,7 +339,7 @@ class DebugClassLoader array_splice($tail, 0, $i + 1); if (!$tail) { - return; + return null; } $tail = \DIRECTORY_SEPARATOR.implode(\DIRECTORY_SEPARATOR, $tail); @@ -349,6 +355,8 @@ class DebugClassLoader ) { return [substr($tail, -$tailLen + 1), substr($real, -$tailLen + 1), substr($real, 0, -$tailLen + 1)]; } + + return null; } /** @@ -396,7 +404,7 @@ class DebugClassLoader } if (isset($dirFiles[$file])) { - return $real .= $dirFiles[$file]; + return $real.$dirFiles[$file]; } $kFile = strtolower($file); @@ -415,7 +423,7 @@ class DebugClassLoader self::$darwinCache[$kDir][1] = $dirFiles; } - return $real .= $dirFiles[$kFile]; + return $real.$dirFiles[$kFile]; } /** diff --git a/lib/symfony/debug/ErrorHandler.php b/lib/symfony/debug/ErrorHandler.php index c7dc3279d..1b39fab5c 100644 --- a/lib/symfony/debug/ErrorHandler.php +++ b/lib/symfony/debug/ErrorHandler.php @@ -382,8 +382,7 @@ class ErrorHandler */ public function handleError($type, $message, $file, $line) { - // @deprecated to be removed in Symfony 5.0 - if (\PHP_VERSION_ID >= 70300 && $message && '"' === $message[0] && 0 === strpos($message, '"continue') && preg_match('/^"continue(?: \d++)?" targeting switch is equivalent to "break(?: \d++)?"\. Did you mean to use "continue(?: \d++)?"\?$/', $message)) { + if (\PHP_VERSION_ID >= 70300 && E_WARNING === $type && '"' === $message[0] && false !== strpos($message, '" targeting switch is equivalent to "break')) { $type = E_DEPRECATED; } @@ -450,7 +449,7 @@ class ErrorHandler self::$silencedErrorCache[$id][$message] = $errorAsException; } if (null === $lightTrace) { - return; + return true; } } else { if ($scope) { @@ -470,7 +469,7 @@ class ErrorHandler } if ($throw) { - if (E_USER_ERROR & $type) { + if (\PHP_VERSION_ID < 70400 && E_USER_ERROR & $type) { for ($i = 1; isset($backtrace[$i]); ++$i) { if (isset($backtrace[$i]['function'], $backtrace[$i]['type'], $backtrace[$i - 1]['function']) && '__toString' === $backtrace[$i]['function'] @@ -599,7 +598,9 @@ class ErrorHandler $this->exceptionHandler = null; try { if (null !== $exceptionHandler) { - return \call_user_func($exceptionHandler, $exception); + $exceptionHandler($exception); + + return; } $handlerException = $handlerException ?: $exception; } catch (\Exception $handlerException) { diff --git a/lib/symfony/debug/Exception/SilencedErrorContext.php b/lib/symfony/debug/Exception/SilencedErrorContext.php index f862b74f4..2bacfd5c9 100644 --- a/lib/symfony/debug/Exception/SilencedErrorContext.php +++ b/lib/symfony/debug/Exception/SilencedErrorContext.php @@ -54,7 +54,7 @@ class SilencedErrorContext implements \JsonSerializable return $this->trace; } - public function JsonSerialize() + public function jsonSerialize() { return [ 'severity' => $this->severity, diff --git a/lib/symfony/debug/FatalErrorHandler/ClassNotFoundFatalErrorHandler.php b/lib/symfony/debug/FatalErrorHandler/ClassNotFoundFatalErrorHandler.php index 45dcc00d5..9bae6f865 100644 --- a/lib/symfony/debug/FatalErrorHandler/ClassNotFoundFatalErrorHandler.php +++ b/lib/symfony/debug/FatalErrorHandler/ClassNotFoundFatalErrorHandler.php @@ -33,11 +33,11 @@ class ClassNotFoundFatalErrorHandler implements FatalErrorHandlerInterface $notFoundSuffix = '\' not found'; $notFoundSuffixLen = \strlen($notFoundSuffix); if ($notFoundSuffixLen > $messageLen) { - return; + return null; } if (0 !== substr_compare($error['message'], $notFoundSuffix, -$notFoundSuffixLen)) { - return; + return null; } foreach (['class', 'interface', 'trait'] as $typeName) { @@ -71,6 +71,8 @@ class ClassNotFoundFatalErrorHandler implements FatalErrorHandlerInterface return new ClassNotFoundException($message, $exception); } + + return null; } /** @@ -196,6 +198,8 @@ class ClassNotFoundFatalErrorHandler implements FatalErrorHandlerInterface return $candidate; } } + + return null; } /** diff --git a/lib/symfony/debug/FatalErrorHandler/UndefinedFunctionFatalErrorHandler.php b/lib/symfony/debug/FatalErrorHandler/UndefinedFunctionFatalErrorHandler.php index 9eddeba5a..77fc7aa26 100644 --- a/lib/symfony/debug/FatalErrorHandler/UndefinedFunctionFatalErrorHandler.php +++ b/lib/symfony/debug/FatalErrorHandler/UndefinedFunctionFatalErrorHandler.php @@ -30,17 +30,17 @@ class UndefinedFunctionFatalErrorHandler implements FatalErrorHandlerInterface $notFoundSuffix = '()'; $notFoundSuffixLen = \strlen($notFoundSuffix); if ($notFoundSuffixLen > $messageLen) { - return; + return null; } if (0 !== substr_compare($error['message'], $notFoundSuffix, -$notFoundSuffixLen)) { - return; + return null; } $prefix = 'Call to undefined function '; $prefixLen = \strlen($prefix); if (0 !== strpos($error['message'], $prefix)) { - return; + return null; } $fullyQualifiedFunctionName = substr($error['message'], $prefixLen, -$notFoundSuffixLen); diff --git a/lib/symfony/debug/FatalErrorHandler/UndefinedMethodFatalErrorHandler.php b/lib/symfony/debug/FatalErrorHandler/UndefinedMethodFatalErrorHandler.php index 1318cb13b..ff2843b68 100644 --- a/lib/symfony/debug/FatalErrorHandler/UndefinedMethodFatalErrorHandler.php +++ b/lib/symfony/debug/FatalErrorHandler/UndefinedMethodFatalErrorHandler.php @@ -28,7 +28,7 @@ class UndefinedMethodFatalErrorHandler implements FatalErrorHandlerInterface { preg_match('/^Call to undefined method (.*)::(.*)\(\)$/', $error['message'], $matches); if (!$matches) { - return; + return null; } $className = $matches[1]; diff --git a/lib/symfony/debug/Tests/DebugClassLoaderTest.php b/lib/symfony/debug/Tests/DebugClassLoaderTest.php index c6bc3f7d8..0388acba0 100644 --- a/lib/symfony/debug/Tests/DebugClassLoaderTest.php +++ b/lib/symfony/debug/Tests/DebugClassLoaderTest.php @@ -59,12 +59,10 @@ class DebugClassLoaderTest extends TestCase $this->fail('DebugClassLoader did not register'); } - /** - * @expectedException \Exception - * @expectedExceptionMessage boo - */ public function testThrowingClass() { + $this->expectException('Exception'); + $this->expectExceptionMessage('boo'); try { class_exists(__NAMESPACE__.'\Fixtures\Throwing'); $this->fail('Exception expected'); @@ -139,21 +137,17 @@ class DebugClassLoaderTest extends TestCase } } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Case mismatch between loaded and declared class names - */ public function testNameCaseMismatch() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Case mismatch between loaded and declared class names'); class_exists(__NAMESPACE__.'\TestingCaseMismatch', true); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Case mismatch between class and real file names - */ public function testFileCaseMismatch() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Case mismatch between class and real file names'); if (!file_exists(__DIR__.'/Fixtures/CaseMismatch.php')) { $this->markTestSkipped('Can only be run on case insensitive filesystems'); } @@ -161,12 +155,10 @@ class DebugClassLoaderTest extends TestCase class_exists(__NAMESPACE__.'\Fixtures\CaseMismatch', true); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Case mismatch between loaded and declared class names - */ public function testPsr4CaseMismatch() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Case mismatch between loaded and declared class names'); class_exists(__NAMESPACE__.'\Fixtures\Psr4CaseMismatch', true); } @@ -447,5 +439,7 @@ class ClassLoader } elseif ('Test\\'.__NAMESPACE__.'\UseTraitWithInternalMethod' === $class) { eval('namespace Test\\'.__NAMESPACE__.'; class UseTraitWithInternalMethod { use \\'.__NAMESPACE__.'\Fixtures\TraitWithInternalMethod; }'); } + + return null; } } diff --git a/lib/symfony/debug/Tests/ErrorHandlerTest.php b/lib/symfony/debug/Tests/ErrorHandlerTest.php index bb7fe413a..2cf75a0e8 100644 --- a/lib/symfony/debug/Tests/ErrorHandlerTest.php +++ b/lib/symfony/debug/Tests/ErrorHandlerTest.php @@ -283,6 +283,10 @@ class ErrorHandlerTest extends TestCase public function testHandleUserError() { + if (\PHP_VERSION_ID >= 70400) { + $this->markTestSkipped('PHP 7.4 allows __toString to throw exceptions'); + } + try { $handler = ErrorHandler::register(); $handler->throwAt(0, true); @@ -573,11 +577,11 @@ class ErrorHandlerTest extends TestCase } /** - * @expectedException \Exception * @group no-hhvm */ public function testCustomExceptionHandler() { + $this->expectException('Exception'); $handler = new ErrorHandler(); $handler->setExceptionHandler(function ($e) use ($handler) { $handler->handleException($e); diff --git a/lib/symfony/debug/Tests/Exception/FlattenExceptionTest.php b/lib/symfony/debug/Tests/Exception/FlattenExceptionTest.php index f755a78cf..0290b05ba 100644 --- a/lib/symfony/debug/Tests/Exception/FlattenExceptionTest.php +++ b/lib/symfony/debug/Tests/Exception/FlattenExceptionTest.php @@ -256,7 +256,7 @@ class FlattenExceptionTest extends TestCase // assertEquals() does not like NAN values. $this->assertEquals($array[$i][0], 'float'); - $this->assertTrue(is_nan($array[$i++][1])); + $this->assertNan($array[$i][1]); } public function testRecursionInArguments() @@ -267,7 +267,7 @@ class FlattenExceptionTest extends TestCase $flattened = FlattenException::create($exception); $trace = $flattened->getTrace(); - $this->assertContains('*DEEP NESTED ARRAY*', serialize($trace)); + $this->assertStringContainsString('*DEEP NESTED ARRAY*', serialize($trace)); } public function testTooBigArray() @@ -291,8 +291,8 @@ class FlattenExceptionTest extends TestCase $serializeTrace = serialize($trace); - $this->assertContains('*SKIPPED over 10000 entries*', $serializeTrace); - $this->assertNotContains('*value1*', $serializeTrace); + $this->assertStringContainsString('*SKIPPED over 10000 entries*', $serializeTrace); + $this->assertStringNotContainsString('*value1*', $serializeTrace); } private function createException($foo) diff --git a/lib/symfony/debug/Tests/ExceptionHandlerTest.php b/lib/symfony/debug/Tests/ExceptionHandlerTest.php index 8a1966495..7a029e06f 100644 --- a/lib/symfony/debug/Tests/ExceptionHandlerTest.php +++ b/lib/symfony/debug/Tests/ExceptionHandlerTest.php @@ -39,8 +39,8 @@ class ExceptionHandlerTest extends TestCase $handler->sendPhpResponse(new \RuntimeException('Foo')); $response = ob_get_clean(); - $this->assertContains('Whoops, looks like something went wrong.', $response); - $this->assertNotContains('
', $response); + $this->assertStringContainsString('Whoops, looks like something went wrong.', $response); + $this->assertStringNotContainsString('
', $response); $handler = new ExceptionHandler(true); @@ -48,8 +48,8 @@ class ExceptionHandlerTest extends TestCase $handler->sendPhpResponse(new \RuntimeException('Foo')); $response = ob_get_clean(); - $this->assertContains('Whoops, looks like something went wrong.', $response); - $this->assertContains('
', $response); + $this->assertStringContainsString('Whoops, looks like something went wrong.', $response); + $this->assertStringContainsString('
', $response); } public function testStatusCode() @@ -60,7 +60,7 @@ class ExceptionHandlerTest extends TestCase $handler->sendPhpResponse(new NotFoundHttpException('Foo')); $response = ob_get_clean(); - $this->assertContains('Sorry, the page you are looking for could not be found.', $response); + $this->assertStringContainsString('Sorry, the page you are looking for could not be found.', $response); $expectedHeaders = [ ['HTTP/1.0 404', true, null], @@ -116,7 +116,7 @@ class ExceptionHandlerTest extends TestCase }); $handler->handle(new \Exception()); - ob_end_flush(); // Necessary because of this PHP bug : https://bugs.php.net/bug.php?id=76563 + ob_end_flush(); // Necessary because of this PHP bug : https://bugs.php.net/76563 $this->assertSame('ccc', ob_get_clean()); } @@ -157,7 +157,7 @@ class ExceptionHandlerTest extends TestCase private function assertThatTheExceptionWasOutput($content, $expectedClass, $expectedTitle, $expectedMessage) { - $this->assertContains(sprintf('%s', $expectedClass, $expectedTitle), $content); - $this->assertContains(sprintf('

%s

', $expectedMessage), $content); + $this->assertStringContainsString(sprintf('%s', $expectedClass, $expectedTitle), $content); + $this->assertStringContainsString(sprintf('

%s

', $expectedMessage), $content); } } diff --git a/lib/symfony/dependency-injection/Argument/RewindableGenerator.php b/lib/symfony/dependency-injection/Argument/RewindableGenerator.php index f8f771d62..b00a36c34 100644 --- a/lib/symfony/dependency-injection/Argument/RewindableGenerator.php +++ b/lib/symfony/dependency-injection/Argument/RewindableGenerator.php @@ -20,7 +20,6 @@ class RewindableGenerator implements \IteratorAggregate, \Countable private $count; /** - * @param callable $generator * @param int|callable $count */ public function __construct(callable $generator, $count) diff --git a/lib/symfony/dependency-injection/ChildDefinition.php b/lib/symfony/dependency-injection/ChildDefinition.php index 29fbd48f2..123b38747 100644 --- a/lib/symfony/dependency-injection/ChildDefinition.php +++ b/lib/symfony/dependency-injection/ChildDefinition.php @@ -89,7 +89,7 @@ class ChildDefinition extends Definition * @param int|string $index * @param mixed $value * - * @return self the current instance + * @return $this * * @throws InvalidArgumentException when $index isn't an integer */ diff --git a/lib/symfony/dependency-injection/Compiler/AbstractRecursivePass.php b/lib/symfony/dependency-injection/Compiler/AbstractRecursivePass.php index cff09d57d..5ca2b2246 100644 --- a/lib/symfony/dependency-injection/Compiler/AbstractRecursivePass.php +++ b/lib/symfony/dependency-injection/Compiler/AbstractRecursivePass.php @@ -81,8 +81,7 @@ abstract class AbstractRecursivePass implements CompilerPassInterface } /** - * @param Definition $definition - * @param bool $required + * @param bool $required * * @return \ReflectionFunctionAbstract|null * @@ -90,6 +89,10 @@ abstract class AbstractRecursivePass implements CompilerPassInterface */ protected function getConstructor(Definition $definition, $required) { + if ($definition->isSynthetic()) { + return null; + } + if (\is_string($factory = $definition->getFactory())) { if (!\function_exists($factory)) { throw new RuntimeException(sprintf('Invalid service "%s": function "%s" does not exist.', $this->currentId, $factory)); @@ -137,8 +140,7 @@ abstract class AbstractRecursivePass implements CompilerPassInterface } /** - * @param Definition $definition - * @param string $method + * @param string $method * * @throws RuntimeException * diff --git a/lib/symfony/dependency-injection/Compiler/AnalyzeServiceReferencesPass.php b/lib/symfony/dependency-injection/Compiler/AnalyzeServiceReferencesPass.php index fc4047f90..bff9d4207 100644 --- a/lib/symfony/dependency-injection/Compiler/AnalyzeServiceReferencesPass.php +++ b/lib/symfony/dependency-injection/Compiler/AnalyzeServiceReferencesPass.php @@ -122,7 +122,7 @@ class AnalyzeServiceReferencesPass extends AbstractRecursivePass implements Repe $this->lazy = false; $byConstructor = $this->byConstructor; - $this->byConstructor = true; + $this->byConstructor = $isRoot || $byConstructor; $this->processValue($value->getFactory()); $this->processValue($value->getArguments()); $this->byConstructor = $byConstructor; @@ -156,7 +156,7 @@ class AnalyzeServiceReferencesPass extends AbstractRecursivePass implements Repe } if (!$this->container->hasDefinition($id)) { - return; + return null; } return $this->container->normalizeId($id); diff --git a/lib/symfony/dependency-injection/Compiler/AutowirePass.php b/lib/symfony/dependency-injection/Compiler/AutowirePass.php index c8e7a0f57..91b279c77 100644 --- a/lib/symfony/dependency-injection/Compiler/AutowirePass.php +++ b/lib/symfony/dependency-injection/Compiler/AutowirePass.php @@ -79,8 +79,6 @@ class AutowirePass extends AbstractRecursivePass /** * Creates a resource to help know if this service has changed. * - * @param \ReflectionClass $reflectionClass - * * @return AutowireServiceResource * * @deprecated since version 3.3, to be removed in 4.0. Use ContainerBuilder::getReflectionClass() instead. @@ -168,9 +166,6 @@ class AutowirePass extends AbstractRecursivePass } /** - * @param \ReflectionClass $reflectionClass - * @param array $methodCalls - * * @return array */ private function autowireCalls(\ReflectionClass $reflectionClass, array $methodCalls) @@ -205,9 +200,6 @@ class AutowirePass extends AbstractRecursivePass /** * Autowires the constructor or a method. * - * @param \ReflectionFunctionAbstract $reflectionMethod - * @param array $arguments - * * @return array The autowired arguments * * @throws AutowiringFailedException @@ -318,7 +310,7 @@ class AutowirePass extends AbstractRecursivePass } if (!$reference->canBeAutoregistered() || isset($this->types[$type]) || isset($this->ambiguousServiceTypes[$type])) { - return; + return null; } if (isset($this->autowired[$type])) { @@ -328,6 +320,8 @@ class AutowirePass extends AbstractRecursivePass if (!$this->strictMode) { return $this->createAutowiredDefinition($type); } + + return null; } /** @@ -348,8 +342,7 @@ class AutowirePass extends AbstractRecursivePass /** * Populates the list of available types for a given definition. * - * @param string $id - * @param Definition $definition + * @param string $id */ private function populateAvailableType($id, Definition $definition, $onlyAutowiringTypes) { @@ -425,7 +418,7 @@ class AutowirePass extends AbstractRecursivePass private function createAutowiredDefinition($type) { if (!($typeHint = $this->container->getReflectionClass($type, false)) || !$typeHint->isInstantiable()) { - return; + return null; } $currentId = $this->currentId; @@ -445,7 +438,7 @@ class AutowirePass extends AbstractRecursivePass $this->lastFailure = $e->getMessage(); $this->container->log($this, $this->lastFailure); - return; + return null; } finally { $this->throwOnAutowiringException = $originalThrowSetting; $this->currentId = $currentId; @@ -518,7 +511,7 @@ class AutowirePass extends AbstractRecursivePass } elseif ($reference->getRequiringClass() && !$reference->canBeAutoregistered() && !$this->strictMode) { return ' It cannot be auto-registered because it is from a different root namespace.'; } else { - return; + return ''; } return sprintf(' You should maybe alias this %s to %s.', class_exists($type, false) ? 'class' : 'interface', $message); @@ -572,5 +565,7 @@ class AutowirePass extends AbstractRecursivePass if ($aliases) { return sprintf('Try changing the type-hint%s to "%s" instead.', $extraContext, $aliases[0]); } + + return null; } } diff --git a/lib/symfony/dependency-injection/Compiler/CheckArgumentsValidityPass.php b/lib/symfony/dependency-injection/Compiler/CheckArgumentsValidityPass.php index feb05c049..30a6f524a 100644 --- a/lib/symfony/dependency-injection/Compiler/CheckArgumentsValidityPass.php +++ b/lib/symfony/dependency-injection/Compiler/CheckArgumentsValidityPass.php @@ -81,5 +81,7 @@ class CheckArgumentsValidityPass extends AbstractRecursivePass } } } + + return null; } } diff --git a/lib/symfony/dependency-injection/Compiler/Compiler.php b/lib/symfony/dependency-injection/Compiler/Compiler.php index a6ae94d8c..bf0d9c3ea 100644 --- a/lib/symfony/dependency-injection/Compiler/Compiler.php +++ b/lib/symfony/dependency-injection/Compiler/Compiler.php @@ -73,9 +73,8 @@ class Compiler /** * Adds a pass to the PassConfig. * - * @param CompilerPassInterface $pass A compiler pass - * @param string $type The type of the pass - * @param int $priority Used to sort the passes + * @param CompilerPassInterface $pass A compiler pass + * @param string $type The type of the pass */ public function addPass(CompilerPassInterface $pass, $type = PassConfig::TYPE_BEFORE_OPTIMIZATION/*, int $priority = 0*/) { diff --git a/lib/symfony/dependency-injection/Compiler/PassConfig.php b/lib/symfony/dependency-injection/Compiler/PassConfig.php index 77f4e9531..323faad57 100644 --- a/lib/symfony/dependency-injection/Compiler/PassConfig.php +++ b/lib/symfony/dependency-injection/Compiler/PassConfig.php @@ -113,9 +113,8 @@ class PassConfig /** * Adds a pass. * - * @param CompilerPassInterface $pass A Compiler pass - * @param string $type The pass type - * @param int $priority Used to sort the passes + * @param CompilerPassInterface $pass A Compiler pass + * @param string $type The pass type * * @throws InvalidArgumentException when a pass type doesn't exist */ diff --git a/lib/symfony/dependency-injection/Compiler/PriorityTaggedServiceTrait.php b/lib/symfony/dependency-injection/Compiler/PriorityTaggedServiceTrait.php index daff3495a..c7e12536e 100644 --- a/lib/symfony/dependency-injection/Compiler/PriorityTaggedServiceTrait.php +++ b/lib/symfony/dependency-injection/Compiler/PriorityTaggedServiceTrait.php @@ -28,11 +28,10 @@ trait PriorityTaggedServiceTrait * and knowing that the \SplPriorityQueue class does not respect the FIFO method, * we should not use that class. * - * @see https://bugs.php.net/bug.php?id=53710 - * @see https://bugs.php.net/bug.php?id=60926 + * @see https://bugs.php.net/53710 + * @see https://bugs.php.net/60926 * - * @param string $tagName - * @param ContainerBuilder $container + * @param string $tagName * * @return Reference[] */ diff --git a/lib/symfony/dependency-injection/Compiler/ResolveReferencesToAliasesPass.php b/lib/symfony/dependency-injection/Compiler/ResolveReferencesToAliasesPass.php index b80e45256..2559dcf10 100644 --- a/lib/symfony/dependency-injection/Compiler/ResolveReferencesToAliasesPass.php +++ b/lib/symfony/dependency-injection/Compiler/ResolveReferencesToAliasesPass.php @@ -56,8 +56,7 @@ class ResolveReferencesToAliasesPass extends AbstractRecursivePass /** * Resolves an alias into a definition id. * - * @param string $id The definition or alias id to resolve - * @param ContainerBuilder $container + * @param string $id The definition or alias id to resolve * * @return string The definition id with aliases resolved */ diff --git a/lib/symfony/dependency-injection/Compiler/ServiceLocatorTagPass.php b/lib/symfony/dependency-injection/Compiler/ServiceLocatorTagPass.php index 51de4d7ac..a7427c5a5 100644 --- a/lib/symfony/dependency-injection/Compiler/ServiceLocatorTagPass.php +++ b/lib/symfony/dependency-injection/Compiler/ServiceLocatorTagPass.php @@ -41,6 +41,8 @@ final class ServiceLocatorTagPass extends AbstractRecursivePass throw new InvalidArgumentException(sprintf('Invalid definition for service "%s": an array of references is expected as first argument when the "container.service_locator" tag is set.', $this->currentId)); } + $i = 0; + foreach ($arguments[0] as $k => $v) { if ($v instanceof ServiceClosureArgument) { continue; @@ -49,10 +51,13 @@ final class ServiceLocatorTagPass extends AbstractRecursivePass throw new InvalidArgumentException(sprintf('Invalid definition for service "%s": an array of references is expected as first argument when the "container.service_locator" tag is set, "%s" found for key "%s".', $this->currentId, \is_object($v) ? \get_class($v) : \gettype($v), $k)); } - if (\is_int($k)) { + if ($i === $k) { unset($arguments[0][$k]); $k = (string) $v; + ++$i; + } elseif (\is_int($k)) { + $i = null; } $arguments[0][$k] = new ServiceClosureArgument($v); } @@ -76,9 +81,8 @@ final class ServiceLocatorTagPass extends AbstractRecursivePass } /** - * @param ContainerBuilder $container - * @param Reference[] $refMap - * @param string|null $callerId + * @param Reference[] $refMap + * @param string|null $callerId * * @return Reference */ diff --git a/lib/symfony/dependency-injection/Compiler/ServiceReferenceGraph.php b/lib/symfony/dependency-injection/Compiler/ServiceReferenceGraph.php index 23d4745ed..e419e297e 100644 --- a/lib/symfony/dependency-injection/Compiler/ServiceReferenceGraph.php +++ b/lib/symfony/dependency-injection/Compiler/ServiceReferenceGraph.php @@ -89,9 +89,6 @@ class ServiceReferenceGraph * @param string $destId * @param mixed $destValue * @param string $reference - * @param bool $lazy - * @param bool $weak - * @param bool $byConstructor */ public function connect($sourceId, $sourceValue, $destId, $destValue = null, $reference = null/*, bool $lazy = false, bool $weak = false, bool $byConstructor = false*/) { diff --git a/lib/symfony/dependency-injection/Compiler/ServiceReferenceGraphEdge.php b/lib/symfony/dependency-injection/Compiler/ServiceReferenceGraphEdge.php index 5b8c84b6d..911e7a5f5 100644 --- a/lib/symfony/dependency-injection/Compiler/ServiceReferenceGraphEdge.php +++ b/lib/symfony/dependency-injection/Compiler/ServiceReferenceGraphEdge.php @@ -28,12 +28,10 @@ class ServiceReferenceGraphEdge private $byConstructor; /** - * @param ServiceReferenceGraphNode $sourceNode - * @param ServiceReferenceGraphNode $destNode - * @param mixed $value - * @param bool $lazy - * @param bool $weak - * @param bool $byConstructor + * @param mixed $value + * @param bool $lazy + * @param bool $weak + * @param bool $byConstructor */ public function __construct(ServiceReferenceGraphNode $sourceNode, ServiceReferenceGraphNode $destNode, $value = null, $lazy = false, $weak = false, $byConstructor = false) { diff --git a/lib/symfony/dependency-injection/Container.php b/lib/symfony/dependency-injection/Container.php index f2215acf1..b9f44b0bf 100644 --- a/lib/symfony/dependency-injection/Container.php +++ b/lib/symfony/dependency-injection/Container.php @@ -162,8 +162,8 @@ class Container implements ResettableContainerInterface * Setting a synthetic service to null resets it: has() returns false and get() * behaves in the same way as if the service was never created. * - * @param string $id The service identifier - * @param object $service The service instance + * @param string $id The service identifier + * @param object|null $service The service instance */ public function set($id, $service) { @@ -263,7 +263,7 @@ class Container implements ResettableContainerInterface * @param string $id The service identifier * @param int $invalidBehavior The behavior when the service does not exist * - * @return object The associated service + * @return object|null The associated service * * @throws ServiceCircularReferenceException When a circular reference is detected * @throws ServiceNotFoundException When the service is not defined @@ -405,7 +405,7 @@ class Container implements ResettableContainerInterface } $ids[] = 'service_container'; - return array_map('strval', array_unique(array_merge($ids, array_keys($this->methodMap), array_keys($this->fileMap), array_keys($this->services)))); + return array_map('strval', array_unique(array_merge($ids, array_keys($this->methodMap), array_keys($this->fileMap), array_keys($this->aliases), array_keys($this->services)))); } /** @@ -444,8 +444,6 @@ class Container implements ResettableContainerInterface /** * Creates a service by requiring its factory file. - * - * @return object The service created by the file */ protected function load($file) { diff --git a/lib/symfony/dependency-injection/ContainerBuilder.php b/lib/symfony/dependency-injection/ContainerBuilder.php index 73145fd8d..f9bfcb521 100644 --- a/lib/symfony/dependency-injection/ContainerBuilder.php +++ b/lib/symfony/dependency-injection/ContainerBuilder.php @@ -354,14 +354,14 @@ class ContainerBuilder extends Container implements TaggedContainerInterface public function getReflectionClass($class, $throw = true) { if (!$class = $this->getParameterBag()->resolveValue($class)) { - return; + return null; } if (isset(self::$internalTypes[$class])) { return null; } - $resource = null; + $resource = $classReflector = null; try { if (isset($this->classReflectors[$class])) { @@ -376,7 +376,6 @@ class ContainerBuilder extends Container implements TaggedContainerInterface if ($throw) { throw $e; } - $classReflector = false; } if ($this->trackResources) { @@ -519,8 +518,8 @@ class ContainerBuilder extends Container implements TaggedContainerInterface /** * Sets a service. * - * @param string $id The service identifier - * @param object $service The service instance + * @param string $id The service identifier + * @param object|null $service The service instance * * @throws BadMethodCallException When this ContainerBuilder is compiled */ @@ -571,7 +570,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface * @param string $id The service identifier * @param int $invalidBehavior The behavior when the service does not exist * - * @return object The associated service + * @return object|null The associated service * * @throws InvalidArgumentException when no definitions are available * @throws ServiceCircularReferenceException When a circular reference is detected @@ -621,7 +620,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface $definition = $this->getDefinition($id); } catch (ServiceNotFoundException $e) { if (ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE !== $invalidBehavior) { - return; + return null; } throw $e; @@ -946,8 +945,8 @@ class ContainerBuilder extends Container implements TaggedContainerInterface * This methods allows for simple registration of service definition * with a fluid interface. * - * @param string $id The service identifier - * @param string $class|null The service class + * @param string $id The service identifier + * @param string|null $class The service class * * @return Definition A Definition instance */ @@ -1104,7 +1103,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface * @param string $id The service identifier * @param bool $tryProxy Whether to try proxying the service with a lazy proxy * - * @return object The service described by the service definition + * @return mixed The service described by the service definition * * @throws RuntimeException When the factory definition is incomplete * @throws RuntimeException When the service is a synthetic service @@ -1650,8 +1649,7 @@ class ContainerBuilder extends Container implements TaggedContainerInterface /** * Shares a given service in the container. * - * @param Definition $definition - * @param object $service + * @param mixed $service * @param string|null $id */ private function shareService(Definition $definition, $service, $id, array &$inlineServices) diff --git a/lib/symfony/dependency-injection/ContainerInterface.php b/lib/symfony/dependency-injection/ContainerInterface.php index 2274ec7bb..c5ab4c2ed 100644 --- a/lib/symfony/dependency-injection/ContainerInterface.php +++ b/lib/symfony/dependency-injection/ContainerInterface.php @@ -32,8 +32,8 @@ interface ContainerInterface extends PsrContainerInterface /** * Sets a service. * - * @param string $id The service identifier - * @param object $service The service instance + * @param string $id The service identifier + * @param object|null $service The service instance */ public function set($id, $service); @@ -43,7 +43,7 @@ interface ContainerInterface extends PsrContainerInterface * @param string $id The service identifier * @param int $invalidBehavior The behavior when the service does not exist * - * @return object The associated service + * @return object|null The associated service * * @throws ServiceCircularReferenceException When a circular reference is detected * @throws ServiceNotFoundException When the service is not defined diff --git a/lib/symfony/dependency-injection/Definition.php b/lib/symfony/dependency-injection/Definition.php index ee5803471..c7d204948 100644 --- a/lib/symfony/dependency-injection/Definition.php +++ b/lib/symfony/dependency-injection/Definition.php @@ -796,7 +796,7 @@ class Definition /** * Gets the configurator to call after the service is fully initialized. * - * @return callable|null The PHP callable to call + * @return callable|array|null */ public function getConfigurator() { @@ -936,8 +936,6 @@ class Definition * injected in the matching parameters (of the constructor, of methods * called and of controller actions). * - * @param array $bindings - * * @return $this */ public function setBindings(array $bindings) diff --git a/lib/symfony/dependency-injection/Dumper/DumperInterface.php b/lib/symfony/dependency-injection/Dumper/DumperInterface.php index 1ea775ddf..8abc19250 100644 --- a/lib/symfony/dependency-injection/Dumper/DumperInterface.php +++ b/lib/symfony/dependency-injection/Dumper/DumperInterface.php @@ -21,9 +21,7 @@ interface DumperInterface /** * Dumps the service container. * - * @param array $options An array of options - * - * @return string The representation of the service container + * @return string|array The representation of the service container */ public function dump(array $options = []); } diff --git a/lib/symfony/dependency-injection/Dumper/PhpDumper.php b/lib/symfony/dependency-injection/Dumper/PhpDumper.php index 73c868f1e..7596b9953 100644 --- a/lib/symfony/dependency-injection/Dumper/PhpDumper.php +++ b/lib/symfony/dependency-injection/Dumper/PhpDumper.php @@ -219,7 +219,7 @@ EOF; foreach ($ids as $id) { $c .= ' '.$this->doExport($id)." => true,\n"; } - $files['removed-ids.php'] = $c .= "];\n"; + $files['removed-ids.php'] = $c."];\n"; } foreach ($this->generateServiceFiles() as $file => $c) { @@ -302,10 +302,10 @@ EOF; return $this->proxyDumper; } - private function analyzeCircularReferences($sourceId, array $edges, &$checkedNodes, &$currentPath = []) + private function analyzeCircularReferences($sourceId, array $edges, &$checkedNodes, &$currentPath = [], $byConstructor = true) { $checkedNodes[$sourceId] = true; - $currentPath[$sourceId] = $sourceId; + $currentPath[$sourceId] = $byConstructor; foreach ($edges as $edge) { $node = $edge->getDestNode(); @@ -314,44 +314,52 @@ EOF; if (!$node->getValue() instanceof Definition || $sourceId === $id || $edge->isLazy() || $edge->isWeak()) { // no-op } elseif (isset($currentPath[$id])) { - $currentId = $id; - foreach (array_reverse($currentPath) as $parentId) { - $this->circularReferences[$parentId][$currentId] = $currentId; - if ($parentId === $id) { - break; - } - $currentId = $parentId; - } + $this->addCircularReferences($id, $currentPath, $edge->isReferencedByConstructor()); } elseif (!isset($checkedNodes[$id])) { - $this->analyzeCircularReferences($id, $node->getOutEdges(), $checkedNodes, $currentPath); + $this->analyzeCircularReferences($id, $node->getOutEdges(), $checkedNodes, $currentPath, $edge->isReferencedByConstructor()); } elseif (isset($this->circularReferences[$id])) { - $this->connectCircularReferences($id, $currentPath); + $this->connectCircularReferences($id, $currentPath, $edge->isReferencedByConstructor()); } } unset($currentPath[$sourceId]); } - private function connectCircularReferences($sourceId, &$currentPath, &$subPath = []) + private function connectCircularReferences($sourceId, &$currentPath, $byConstructor, &$subPath = []) { - $subPath[$sourceId] = $sourceId; - $currentPath[$sourceId] = $sourceId; + $currentPath[$sourceId] = $subPath[$sourceId] = $byConstructor; - foreach ($this->circularReferences[$sourceId] as $id) { + foreach ($this->circularReferences[$sourceId] as $id => $byConstructor) { if (isset($currentPath[$id])) { - $currentId = $id; - foreach (array_reverse($currentPath) as $parentId) { - $this->circularReferences[$parentId][$currentId] = $currentId; - if ($parentId === $id) { - break; - } - $currentId = $parentId; - } + $this->addCircularReferences($id, $currentPath, $byConstructor); } elseif (!isset($subPath[$id]) && isset($this->circularReferences[$id])) { - $this->connectCircularReferences($id, $currentPath, $subPath); + $this->connectCircularReferences($id, $currentPath, $byConstructor, $subPath); } } - unset($currentPath[$sourceId]); - unset($subPath[$sourceId]); + unset($currentPath[$sourceId], $subPath[$sourceId]); + } + + private function addCircularReferences($id, $currentPath, $byConstructor) + { + $currentPath[$id] = $byConstructor; + $circularRefs = []; + + foreach (array_reverse($currentPath) as $parentId => $v) { + $byConstructor = $byConstructor && $v; + $circularRefs[] = $parentId; + + if ($parentId === $id) { + break; + } + } + + $currentId = $id; + foreach ($circularRefs as $parentId) { + if (empty($this->circularReferences[$parentId][$currentId])) { + $this->circularReferences[$parentId][$currentId] = $byConstructor; + } + + $currentId = $parentId; + } } private function collectLineage($class, array &$lineage) @@ -462,9 +470,8 @@ EOF; /** * Generates the service instance. * - * @param string $id - * @param Definition $definition - * @param bool $isSimpleInstance + * @param string $id + * @param bool $isSimpleInstance * * @return string * @@ -501,8 +508,6 @@ EOF; /** * Checks if the definition is a trivial instance. * - * @param Definition $definition - * * @return bool */ private function isTrivialInstance(Definition $definition) @@ -546,8 +551,7 @@ EOF; /** * Adds method calls to a service definition. * - * @param Definition $definition - * @param string $variableName + * @param string $variableName * * @return string */ @@ -579,8 +583,7 @@ EOF; /** * Adds configurator definition. * - * @param Definition $definition - * @param string $variableName + * @param string $variableName * * @return string */ @@ -616,9 +619,8 @@ EOF; /** * Adds a service. * - * @param string $id - * @param Definition $definition - * @param string &$file + * @param string $id + * @param string &$file * * @return string */ @@ -661,7 +663,6 @@ EOF; $autowired = $definition->isAutowired() ? ' autowired' : ''; if ($definition->isLazy()) { - unset($this->circularReferences[$id]); $lazyInitialization = '$lazyLoad = true'; } else { $lazyInitialization = ''; @@ -736,12 +737,12 @@ EOF; private function addInlineReference($id, Definition $definition, $targetId, $forConstructor) { - list($callCount, $behavior) = $this->serviceCalls[$targetId]; - while ($this->container->hasAlias($targetId)) { $targetId = (string) $this->container->getAlias($targetId); } + list($callCount, $behavior) = $this->serviceCalls[$targetId]; + if ($id === $targetId) { return $this->addInlineService($id, $definition, $definition); } @@ -750,9 +751,13 @@ EOF; return ''; } - $hasSelfRef = isset($this->circularReferences[$id][$targetId]); - $forConstructor = $forConstructor && !isset($this->definitionVariables[$definition]); - $code = $hasSelfRef && !$forConstructor ? $this->addInlineService($id, $definition, $definition) : ''; + $hasSelfRef = isset($this->circularReferences[$id][$targetId]) && !isset($this->definitionVariables[$definition]); + + if ($hasSelfRef && !$forConstructor && !$forConstructor = !$this->circularReferences[$id][$targetId]) { + $code = $this->addInlineService($id, $definition, $definition); + } else { + $code = ''; + } if (isset($this->referenceVariables[$targetId]) || (2 > $callCount && (!$hasSelfRef || !$forConstructor))) { return $code; @@ -785,15 +790,23 @@ EOTXT private function addInlineService($id, Definition $definition, Definition $inlineDef = null, $forConstructor = true) { - $isSimpleInstance = $isRootInstance = null === $inlineDef; + $code = ''; + + if ($isSimpleInstance = $isRootInstance = null === $inlineDef) { + foreach ($this->serviceCalls as $targetId => list($callCount, $behavior, $byConstructor)) { + if ($byConstructor && isset($this->circularReferences[$id][$targetId]) && !$this->circularReferences[$id][$targetId]) { + $code .= $this->addInlineReference($id, $definition, $targetId, $forConstructor); + } + } + } if (isset($this->definitionVariables[$inlineDef = $inlineDef ?: $definition])) { - return ''; + return $code; } $arguments = [$inlineDef->getArguments(), $inlineDef->getFactory()]; - $code = $this->addInlineVariables($id, $definition, $arguments, $forConstructor); + $code .= $this->addInlineVariables($id, $definition, $arguments, $forConstructor); if ($arguments = array_filter([$inlineDef->getProperties(), $inlineDef->getMethodCalls(), $inlineDef->getConfigurator()])) { $isSimpleInstance = false; @@ -950,7 +963,7 @@ $bagClass */ class $class extends $baseClass { - private \$parameters; + private \$parameters = []; private \$targetDirs = []; public function __construct() @@ -1452,7 +1465,6 @@ EOF; /** * Exports parameters. * - * @param array $parameters * @param string $path * @param int $indent * @@ -1550,7 +1562,7 @@ EOF; return implode(' && ', $conditions); } - private function getDefinitionsFromArguments(array $arguments, \SplObjectStorage $definitions = null, array &$calls = []) + private function getDefinitionsFromArguments(array $arguments, \SplObjectStorage $definitions = null, array &$calls = [], $byConstructor = null) { if (null === $definitions) { $definitions = new \SplObjectStorage(); @@ -1558,12 +1570,16 @@ EOF; foreach ($arguments as $argument) { if (\is_array($argument)) { - $this->getDefinitionsFromArguments($argument, $definitions, $calls); + $this->getDefinitionsFromArguments($argument, $definitions, $calls, $byConstructor); } elseif ($argument instanceof Reference) { $id = $this->container->normalizeId($argument); + while ($this->container->hasAlias($id)) { + $id = (string) $this->container->getAlias($id); + } + if (!isset($calls[$id])) { - $calls[$id] = [0, $argument->getInvalidBehavior()]; + $calls[$id] = [0, $argument->getInvalidBehavior(), $byConstructor]; } else { $calls[$id][1] = min($calls[$id][1], $argument->getInvalidBehavior()); } @@ -1575,8 +1591,10 @@ EOF; $definitions[$argument] = 1 + $definitions[$argument]; } else { $definitions[$argument] = 1; - $arguments = [$argument->getArguments(), $argument->getFactory(), $argument->getProperties(), $argument->getMethodCalls(), $argument->getConfigurator()]; - $this->getDefinitionsFromArguments($arguments, $definitions, $calls); + $arguments = [$argument->getArguments(), $argument->getFactory()]; + $this->getDefinitionsFromArguments($arguments, $definitions, $calls, null === $byConstructor || $byConstructor); + $arguments = [$argument->getProperties(), $argument->getMethodCalls(), $argument->getConfigurator()]; + $this->getDefinitionsFromArguments($arguments, $definitions, $calls, null !== $byConstructor && $byConstructor); } } @@ -1717,6 +1735,11 @@ EOF; return '$'.$value; } elseif ($value instanceof Reference) { $id = $this->container->normalizeId($value); + + while ($this->container->hasAlias($id)) { + $id = (string) $this->container->getAlias($id); + } + if (null !== $this->referenceVariables && isset($this->referenceVariables[$id])) { return $this->dumpValue($this->referenceVariables[$id], $interpolate); } diff --git a/lib/symfony/dependency-injection/Dumper/XmlDumper.php b/lib/symfony/dependency-injection/Dumper/XmlDumper.php index 67b6dbebb..cfc932843 100644 --- a/lib/symfony/dependency-injection/Dumper/XmlDumper.php +++ b/lib/symfony/dependency-injection/Dumper/XmlDumper.php @@ -90,9 +90,8 @@ class XmlDumper extends Dumper /** * Adds a service. * - * @param Definition $definition - * @param string $id - * @param \DOMElement $parent + * @param Definition $definition + * @param string $id */ private function addService($definition, $id, \DOMElement $parent) { @@ -221,9 +220,7 @@ class XmlDumper extends Dumper /** * Adds a service alias. * - * @param string $alias - * @param Alias $id - * @param \DOMElement $parent + * @param string $alias */ private function addServiceAlias($alias, Alias $id, \DOMElement $parent) { @@ -261,10 +258,8 @@ class XmlDumper extends Dumper /** * Converts parameters. * - * @param array $parameters - * @param string $type - * @param \DOMElement $parent - * @param string $keyAttribute + * @param string $type + * @param string $keyAttribute */ private function convertParameters(array $parameters, $type, \DOMElement $parent, $keyAttribute = 'key') { diff --git a/lib/symfony/dependency-injection/Dumper/YamlDumper.php b/lib/symfony/dependency-injection/Dumper/YamlDumper.php index 8f3fcddf3..1e795c7da 100644 --- a/lib/symfony/dependency-injection/Dumper/YamlDumper.php +++ b/lib/symfony/dependency-injection/Dumper/YamlDumper.php @@ -57,8 +57,7 @@ class YamlDumper extends Dumper /** * Adds a service. * - * @param string $id - * @param Definition $definition + * @param string $id * * @return string */ @@ -171,7 +170,6 @@ class YamlDumper extends Dumper * Adds a service alias. * * @param string $alias - * @param Alias $id * * @return string */ @@ -230,9 +228,7 @@ class YamlDumper extends Dumper /** * Dumps callable to YAML format. * - * @param callable $callable - * - * @return callable + * @param mixed $callable */ private function dumpCallable($callable) { @@ -337,8 +333,7 @@ class YamlDumper extends Dumper /** * Prepares parameters. * - * @param array $parameters - * @param bool $escape + * @param bool $escape * * @return array */ diff --git a/lib/symfony/dependency-injection/EnvVarProcessor.php b/lib/symfony/dependency-injection/EnvVarProcessor.php index a23b83436..885408093 100644 --- a/lib/symfony/dependency-injection/EnvVarProcessor.php +++ b/lib/symfony/dependency-injection/EnvVarProcessor.php @@ -65,7 +65,7 @@ class EnvVarProcessor implements EnvVarProcessorInterface if (false !== $i || 'string' !== $prefix) { if (null === $env = $getEnv($name)) { - return; + return null; } } elseif (isset($_ENV[$name])) { $env = $_ENV[$name]; @@ -77,7 +77,7 @@ class EnvVarProcessor implements EnvVarProcessorInterface } if (null === $env = $this->container->getParameter("env($name)")) { - return; + return null; } } diff --git a/lib/symfony/dependency-injection/Extension/Extension.php b/lib/symfony/dependency-injection/Extension/Extension.php index a9389862c..7df483064 100644 --- a/lib/symfony/dependency-injection/Extension/Extension.php +++ b/lib/symfony/dependency-injection/Extension/Extension.php @@ -84,11 +84,12 @@ abstract class Extension implements ExtensionInterface, ConfigurationExtensionIn $class = $container->getReflectionClass($class); $constructor = $class ? $class->getConstructor() : null; - if ($class && (!$constructor || !$constructor->getNumberOfRequiredParameters())) { - return $class->newInstance(); - } + return $class && (!$constructor || !$constructor->getNumberOfRequiredParameters()) ? $class->newInstance() : null; } + /** + * @return array + */ final protected function processConfiguration(ConfigurationInterface $configuration, array $configs) { $processor = new Processor(); diff --git a/lib/symfony/dependency-injection/Extension/ExtensionInterface.php b/lib/symfony/dependency-injection/Extension/ExtensionInterface.php index 18de31272..6a7a2cf02 100644 --- a/lib/symfony/dependency-injection/Extension/ExtensionInterface.php +++ b/lib/symfony/dependency-injection/Extension/ExtensionInterface.php @@ -37,7 +37,7 @@ interface ExtensionInterface /** * Returns the base path for the XSD files. * - * @return string The XSD base path + * @return string|false */ public function getXsdValidationBasePath(); diff --git a/lib/symfony/dependency-injection/LazyProxy/PhpDumper/DumperInterface.php b/lib/symfony/dependency-injection/LazyProxy/PhpDumper/DumperInterface.php index f2d0476f6..3946eafaf 100644 --- a/lib/symfony/dependency-injection/LazyProxy/PhpDumper/DumperInterface.php +++ b/lib/symfony/dependency-injection/LazyProxy/PhpDumper/DumperInterface.php @@ -30,9 +30,7 @@ interface DumperInterface /** * Generates the code to be used to instantiate a proxy in the dumped factory code. * - * @param Definition $definition - * @param string $id Service identifier - * @param string $factoryCode The code to execute to create the service, will be added to the interface in 4.0 + * @param string $id Service identifier * * @return string */ diff --git a/lib/symfony/dependency-injection/LazyProxy/ProxyHelper.php b/lib/symfony/dependency-injection/LazyProxy/ProxyHelper.php index fb21ba2e4..cb19c729c 100644 --- a/lib/symfony/dependency-injection/LazyProxy/ProxyHelper.php +++ b/lib/symfony/dependency-injection/LazyProxy/ProxyHelper.php @@ -37,7 +37,7 @@ class ProxyHelper $type = method_exists($r, 'getReturnType') ? $r->getReturnType() : null; } if (!$type) { - return; + return null; } if (!\is_string($type)) { $name = $type instanceof \ReflectionNamedType ? $type->getName() : $type->__toString(); @@ -53,13 +53,12 @@ class ProxyHelper return $prefix.$name; } if (!$r instanceof \ReflectionMethod) { - return; + return null; } if ('self' === $lcName) { return $prefix.$r->getDeclaringClass()->name; } - if ($parent = $r->getDeclaringClass()->getParentClass()) { - return $prefix.$parent->name; - } + + return ($parent = $r->getDeclaringClass()->getParentClass()) ? $prefix.$parent->name : null; } } diff --git a/lib/symfony/dependency-injection/Loader/FileLoader.php b/lib/symfony/dependency-injection/Loader/FileLoader.php index f0d920189..77cad3c04 100644 --- a/lib/symfony/dependency-injection/Loader/FileLoader.php +++ b/lib/symfony/dependency-injection/Loader/FileLoader.php @@ -86,8 +86,7 @@ abstract class FileLoader extends BaseFileLoader /** * Registers a definition in the container with its instanceof-conditionals. * - * @param string $id - * @param Definition $definition + * @param string $id */ protected function setDefinition($id, Definition $definition) { @@ -150,12 +149,7 @@ abstract class FileLoader extends BaseFileLoader try { $r = $this->container->getReflectionClass($class); } catch (\ReflectionException $e) { - $classes[$class] = sprintf( - 'While discovering services from namespace "%s", an error was thrown when processing the class "%s": "%s".', - $namespace, - $class, - $e->getMessage() - ); + $classes[$class] = $e->getMessage(); continue; } // check to make sure the expected class exists diff --git a/lib/symfony/dependency-injection/Loader/XmlFileLoader.php b/lib/symfony/dependency-injection/Loader/XmlFileLoader.php index 718592d8e..c4b9b69a0 100644 --- a/lib/symfony/dependency-injection/Loader/XmlFileLoader.php +++ b/lib/symfony/dependency-injection/Loader/XmlFileLoader.php @@ -86,8 +86,7 @@ class XmlFileLoader extends FileLoader /** * Parses parameters. * - * @param \DOMDocument $xml - * @param string $file + * @param string $file */ private function parseParameters(\DOMDocument $xml, $file) { @@ -99,8 +98,7 @@ class XmlFileLoader extends FileLoader /** * Parses imports. * - * @param \DOMDocument $xml - * @param string $file + * @param string $file */ private function parseImports(\DOMDocument $xml, $file) { @@ -121,8 +119,7 @@ class XmlFileLoader extends FileLoader /** * Parses multiple definitions. * - * @param \DOMDocument $xml - * @param string $file + * @param string $file */ private function parseDefinitions(\DOMDocument $xml, $file, $defaults) { @@ -193,9 +190,7 @@ class XmlFileLoader extends FileLoader /** * Parses an individual Definition. * - * @param \DOMElement $service - * @param string $file - * @param array $defaults + * @param string $file * * @return Definition|null */ @@ -211,7 +206,7 @@ class XmlFileLoader extends FileLoader $alias->setPublic($defaults['public']); } - return; + return null; } if ($this->isLoadingInstanceof) { @@ -394,9 +389,8 @@ class XmlFileLoader extends FileLoader /** * Processes anonymous services. * - * @param \DOMDocument $xml - * @param string $file - * @param array $defaults + * @param string $file + * @param array $defaults */ private function processAnonymousServices(\DOMDocument $xml, $file, $defaults) { @@ -456,10 +450,9 @@ class XmlFileLoader extends FileLoader /** * Returns arguments as valid php types. * - * @param \DOMElement $node - * @param string $name - * @param string $file - * @param bool $lowercase + * @param string $name + * @param string $file + * @param bool $lowercase * * @return mixed */ @@ -546,8 +539,7 @@ class XmlFileLoader extends FileLoader /** * Get child elements by name. * - * @param \DOMNode $node - * @param mixed $name + * @param mixed $name * * @return \DOMElement[] */ @@ -566,8 +558,6 @@ class XmlFileLoader extends FileLoader /** * Validates a documents XML schema. * - * @param \DOMDocument $dom - * * @return bool * * @throws RuntimeException When extension references a non-existent XSD file @@ -645,8 +635,7 @@ EOF /** * Validates an alias. * - * @param \DOMElement $alias - * @param string $file + * @param string $file */ private function validateAlias(\DOMElement $alias, $file) { @@ -666,8 +655,7 @@ EOF /** * Validates an extension. * - * @param \DOMDocument $dom - * @param string $file + * @param string $file * * @throws InvalidArgumentException When no extension is found corresponding to a tag */ @@ -688,8 +676,6 @@ EOF /** * Loads from an extension. - * - * @param \DOMDocument $xml */ private function loadFromExtensions(\DOMDocument $xml) { @@ -724,7 +710,7 @@ EOF * * @param \DOMElement $element A \DOMElement instance * - * @return array A PHP array + * @return mixed */ public static function convertDomElementToArray(\DOMElement $element) { diff --git a/lib/symfony/dependency-injection/Loader/YamlFileLoader.php b/lib/symfony/dependency-injection/Loader/YamlFileLoader.php index a3a799024..891689bc1 100644 --- a/lib/symfony/dependency-injection/Loader/YamlFileLoader.php +++ b/lib/symfony/dependency-injection/Loader/YamlFileLoader.php @@ -170,7 +170,6 @@ class YamlFileLoader extends FileLoader /** * Parses all imports. * - * @param array $content * @param string $file */ private function parseImports(array $content, $file) @@ -200,7 +199,6 @@ class YamlFileLoader extends FileLoader /** * Parses definitions. * - * @param array $content * @param string $file */ private function parseDefinitions(array $content, $file) @@ -241,7 +239,6 @@ class YamlFileLoader extends FileLoader } /** - * @param array $content * @param string $file * * @return array @@ -306,8 +303,6 @@ class YamlFileLoader extends FileLoader } /** - * @param array $service - * * @return bool */ private function isUsingShortSyntax(array $service) @@ -327,7 +322,6 @@ class YamlFileLoader extends FileLoader * @param string $id * @param array|string $service * @param string $file - * @param array $defaults * * @throws InvalidArgumentException When tags are invalid */ diff --git a/lib/symfony/dependency-injection/ParameterBag/ParameterBag.php b/lib/symfony/dependency-injection/ParameterBag/ParameterBag.php index c4e702181..e13d2824f 100644 --- a/lib/symfony/dependency-injection/ParameterBag/ParameterBag.php +++ b/lib/symfony/dependency-injection/ParameterBag/ParameterBag.php @@ -195,7 +195,7 @@ class ParameterBag implements ParameterBagInterface * @param string $value The string to resolve * @param array $resolving An array of keys that are being resolved (used internally to detect circular references) * - * @return string The resolved string + * @return mixed The resolved string * * @throws ParameterNotFoundException if a placeholder references a parameter that does not exist * @throws ParameterCircularReferenceException if a circular reference if detected diff --git a/lib/symfony/dependency-injection/Tests/ChildDefinitionTest.php b/lib/symfony/dependency-injection/Tests/ChildDefinitionTest.php index cbae0eaaa..509174839 100644 --- a/lib/symfony/dependency-injection/Tests/ChildDefinitionTest.php +++ b/lib/symfony/dependency-injection/Tests/ChildDefinitionTest.php @@ -90,11 +90,9 @@ class ChildDefinitionTest extends TestCase $this->assertSame(['index_0' => 'foo'], $def->getArguments()); } - /** - * @expectedException \InvalidArgumentException - */ public function testReplaceArgumentShouldRequireIntegerIndex() { + $this->expectException('InvalidArgumentException'); $def = new ChildDefinition('foo'); $def->replaceArgument('0', 'foo'); @@ -119,11 +117,9 @@ class ChildDefinitionTest extends TestCase $this->assertSame([0 => 'foo', 1 => 'bar', 'index_1' => 'baz', '$bar' => 'val'], $def->getArguments()); } - /** - * @expectedException \OutOfBoundsException - */ public function testGetArgumentShouldCheckBounds() { + $this->expectException('OutOfBoundsException'); $def = new ChildDefinition('foo'); $def->setArguments([0 => 'foo']); @@ -137,20 +133,16 @@ class ChildDefinitionTest extends TestCase $this->assertInstanceOf(ChildDefinition::class, new DefinitionDecorator('foo')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\BadMethodCallException - */ public function testCannotCallSetAutoconfigured() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\BadMethodCallException'); $def = new ChildDefinition('foo'); $def->setAutoconfigured(true); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\BadMethodCallException - */ public function testCannotCallSetInstanceofConditionals() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\BadMethodCallException'); $def = new ChildDefinition('foo'); $def->setInstanceofConditionals(['Foo' => new ChildDefinition('')]); } diff --git a/lib/symfony/dependency-injection/Tests/Compiler/AnalyzeServiceReferencesPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/AnalyzeServiceReferencesPassTest.php index 0bd94a3e6..66b6e19cc 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/AnalyzeServiceReferencesPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/AnalyzeServiceReferencesPassTest.php @@ -25,28 +25,28 @@ class AnalyzeServiceReferencesPassTest extends TestCase { $container = new ContainerBuilder(); - $a = $container + $container ->register('a') ->addArgument($ref1 = new Reference('b')) ; - $b = $container + $container ->register('b') ->addMethodCall('setA', [$ref2 = new Reference('a')]) ; - $c = $container + $container ->register('c') ->addArgument($ref3 = new Reference('a')) ->addArgument($ref4 = new Reference('b')) ; - $d = $container + $container ->register('d') ->setProperty('foo', $ref5 = new Reference('b')) ; - $e = $container + $container ->register('e') ->setConfigurator([$ref6 = new Reference('b'), 'methodName']) ; diff --git a/lib/symfony/dependency-injection/Tests/Compiler/AutoAliasServicePassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/AutoAliasServicePassTest.php index d029636a7..4e17778f8 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/AutoAliasServicePassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/AutoAliasServicePassTest.php @@ -17,11 +17,9 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; class AutoAliasServicePassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException - */ public function testProcessWithMissingParameter() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException'); $container = new ContainerBuilder(); $container->register('example') @@ -31,11 +29,9 @@ class AutoAliasServicePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - */ public function testProcessWithMissingFormat() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $container = new ContainerBuilder(); $container->register('example') diff --git a/lib/symfony/dependency-injection/Tests/Compiler/AutowirePassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/AutowirePassTest.php index 31fa665ae..c5bcc660a 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/AutowirePassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/AutowirePassTest.php @@ -182,12 +182,10 @@ class AutowirePassTest extends TestCase $this->assertCount(1, $pass->getAutowiringExceptions()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Invalid service "private_service": constructor of class "Symfony\Component\DependencyInjection\Tests\Compiler\PrivateConstructor" must be public. - */ public function testPrivateConstructorThrowsAutowireException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Invalid service "private_service": constructor of class "Symfony\Component\DependencyInjection\Tests\Compiler\PrivateConstructor" must be public.'); $container = new ContainerBuilder(); $container->autowire('private_service', __NAMESPACE__.'\PrivateConstructor'); @@ -196,12 +194,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "a": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\CannotBeAutowired::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists. You should maybe alias this interface to one of these existing services: "c1", "c2", "c3". - */ public function testTypeCollision() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "a": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\CannotBeAutowired::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists. You should maybe alias this interface to one of these existing services: "c1", "c2", "c3".'); $container = new ContainerBuilder(); $container->register('c1', __NAMESPACE__.'\CollisionA'); @@ -214,12 +210,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "a": argument "$k" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotGuessableArgument::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" but no such service exists. You should maybe alias this class to one of these existing services: "a1", "a2". - */ public function testTypeNotGuessable() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "a": argument "$k" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotGuessableArgument::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\Foo" but no such service exists. You should maybe alias this class to one of these existing services: "a1", "a2".'); $container = new ContainerBuilder(); $container->register('a1', __NAMESPACE__.'\Foo'); @@ -231,12 +225,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "a": argument "$k" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotGuessableArgumentForSubclass::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\A" but no such service exists. You should maybe alias this class to one of these existing services: "a1", "a2". - */ public function testTypeNotGuessableWithSubclass() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "a": argument "$k" of method "Symfony\Component\DependencyInjection\Tests\Compiler\NotGuessableArgumentForSubclass::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\A" but no such service exists. You should maybe alias this class to one of these existing services: "a1", "a2".'); $container = new ContainerBuilder(); $container->register('a1', __NAMESPACE__.'\B'); @@ -248,12 +240,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "a": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\CannotBeAutowired::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists. - */ public function testTypeNotGuessableNoServicesFound() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "a": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\CannotBeAutowired::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists.'); $container = new ContainerBuilder(); $aDefinition = $container->register('a', __NAMESPACE__.'\CannotBeAutowired'); @@ -372,12 +362,10 @@ class AutowirePassTest extends TestCase $this->assertCount(0, $container->getDefinition('bar')->getArguments()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "a": argument "$r" of method "Symfony\Component\DependencyInjection\Tests\Compiler\BadTypeHintedArgument::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\NotARealClass" but this class was not found. - */ public function testClassNotFoundThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "a": argument "$r" of method "Symfony\Component\DependencyInjection\Tests\Compiler\BadTypeHintedArgument::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\NotARealClass" but this class was not found.'); $container = new ContainerBuilder(); $aDefinition = $container->register('a', __NAMESPACE__.'\BadTypeHintedArgument'); @@ -389,12 +377,11 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "a": argument "$r" of method "Symfony\Component\DependencyInjection\Tests\Compiler\BadParentTypeHintedArgument::__construct()" has type "Symfony\Component\DependencyInjection\Tests\Compiler\OptionalServiceClass" but this class is missing a parent class (Class Symfony\Bug\NotExistClass not found). - */ public function testParentClassNotFoundThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessageRegExp('{^Cannot autowire service "a": argument "\$r" of method "(Symfony\\\\Component\\\\DependencyInjection\\\\Tests\\\\Compiler\\\\)BadParentTypeHintedArgument::__construct\(\)" has type "\1OptionalServiceClass" but this class is missing a parent class \(Class "?Symfony\\\\Bug\\\\NotExistClass"? not found}'); + $container = new ContainerBuilder(); $aDefinition = $container->register('a', __NAMESPACE__.'\BadParentTypeHintedArgument'); @@ -455,12 +442,10 @@ class AutowirePassTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "arg_no_type_hint": argument "$bar" of method "Symfony\Component\DependencyInjection\Tests\Compiler\MultipleArguments::__construct()" is type-hinted "array", you should configure its value explicitly. - */ public function testScalarArgsCannotBeAutowired() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "arg_no_type_hint": argument "$bar" of method "Symfony\Component\DependencyInjection\Tests\Compiler\MultipleArguments::__construct()" is type-hinted "array", you should configure its value explicitly.'); $container = new ContainerBuilder(); $container->register(A::class); @@ -473,12 +458,10 @@ class AutowirePassTest extends TestCase (new AutowirePass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "arg_no_type_hint": argument "$foo" of method "Symfony\Component\DependencyInjection\Tests\Compiler\MultipleArguments::__construct()" has no type-hint, you should configure its value explicitly. - */ public function testNoTypeArgsCannotBeAutowired() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "arg_no_type_hint": argument "$foo" of method "Symfony\Component\DependencyInjection\Tests\Compiler\MultipleArguments::__construct()" has no type-hint, you should configure its value explicitly.'); $container = new ContainerBuilder(); $container->register(A::class); @@ -606,12 +589,10 @@ class AutowirePassTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @exceptedExceptionMessage Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "setLogger()" does not exist. - */ public function testWithNonExistingSetterAndAutowiring() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass": method "setLogger()" does not exist.'); $container = new ContainerBuilder(); $definition = $container->register(CaseSensitiveClass::class, CaseSensitiveClass::class)->setAutowired(true); @@ -744,12 +725,10 @@ class AutowirePassTest extends TestCase $this->assertSame('Cannot autowire service "setter_injection_collision": argument "$collision" of method "Symfony\Component\DependencyInjection\Tests\Compiler\SetterInjectionCollision::setMultipleInstancesForOneArg()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\CollisionInterface" but no such service exists. You should maybe alias this interface to one of these existing services: "c1", "c2".', $e->getMessage()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "my_service": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\K::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" but no such service exists. Did you create a class that implements this interface? - */ public function testInterfaceWithNoImplementationSuggestToWriteOne() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "my_service": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\K::__construct()" references interface "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" but no such service exists. Did you create a class that implements this interface?'); $container = new ContainerBuilder(); $aDefinition = $container->register('my_service', K::class); @@ -815,10 +794,10 @@ class AutowirePassTest extends TestCase /** * @dataProvider provideNotWireableCalls - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException */ public function testNotWireableCalls($method, $expectedMsg) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); $container = new ContainerBuilder(); $foo = $container->register('foo', NotWireable::class)->setAutowired(true) @@ -832,12 +811,8 @@ class AutowirePassTest extends TestCase $foo->addMethodCall($method, []); } - if (method_exists($this, 'expectException')) { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage($expectedMsg); - } else { - $this->setExpectedException(RuntimeException::class, $expectedMsg); - } + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage($expectedMsg); (new ResolveClassPass())->process($container); (new AutowireRequiredMethodsPass())->process($container); @@ -891,12 +866,10 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. Try changing the type-hint to "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead. - */ public function testExceptionWhenAliasExists() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. Try changing the type-hint to "Symfony\Component\DependencyInjection\Tests\Compiler\IInterface" instead.'); $container = new ContainerBuilder(); // multiple I services... but there *is* IInterface available @@ -911,12 +884,11 @@ class AutowirePassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\AutowiringFailedException - * @expectedExceptionMessage Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. You should maybe alias this class to one of these existing services: "i", "i2". - */ public function testExceptionWhenAliasDoesNotExist() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\AutowiringFailedException'); + $this->expectExceptionMessage('Cannot autowire service "j": argument "$i" of method "Symfony\Component\DependencyInjection\Tests\Compiler\J::__construct()" references class "Symfony\Component\DependencyInjection\Tests\Compiler\I" but no such service exists. You should maybe alias this class to one of these existing services: "i", "i2".'); + $container = new ContainerBuilder(); // multiple I instances... but no IInterface alias diff --git a/lib/symfony/dependency-injection/Tests/Compiler/CheckArgumentsValidityPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/CheckArgumentsValidityPassTest.php index c1e47b308..9554c23bb 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/CheckArgumentsValidityPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/CheckArgumentsValidityPassTest.php @@ -41,11 +41,11 @@ class CheckArgumentsValidityPassTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException * @dataProvider definitionProvider */ public function testException(array $arguments, array $methodCalls) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $definition = $container->register('foo'); $definition->setArguments($arguments); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/CheckCircularReferencesPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/CheckCircularReferencesPassTest.php index 8423c5616..8d501368e 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/CheckCircularReferencesPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/CheckCircularReferencesPassTest.php @@ -21,11 +21,9 @@ use Symfony\Component\DependencyInjection\Reference; class CheckCircularReferencesPassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testProcess() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('a')); @@ -33,11 +31,9 @@ class CheckCircularReferencesPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testProcessWithAliases() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->setAlias('b', 'c'); @@ -46,11 +42,9 @@ class CheckCircularReferencesPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testProcessWithFactory() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container @@ -64,11 +58,9 @@ class CheckCircularReferencesPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testProcessDetectsIndirectCircularReference() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('c')); @@ -77,11 +69,9 @@ class CheckCircularReferencesPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testProcessDetectsIndirectCircularReferenceWithFactory() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); @@ -95,11 +85,9 @@ class CheckCircularReferencesPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testDeepCircularReference() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container->register('a')->addArgument(new Reference('b')); $container->register('b')->addArgument(new Reference('c')); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/CheckDefinitionValidityPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/CheckDefinitionValidityPassTest.php index e1dd60b66..6caa38c7b 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/CheckDefinitionValidityPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/CheckDefinitionValidityPassTest.php @@ -17,22 +17,18 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; class CheckDefinitionValidityPassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - */ public function testProcessDetectsSyntheticNonPublicDefinitions() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $container->register('a')->setSynthetic(true)->setPublic(false); $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - */ public function testProcessDetectsNonSyntheticNonAbstractDefinitionWithoutClass() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $container->register('a')->setSynthetic(false)->setAbstract(false); @@ -65,22 +61,18 @@ class CheckDefinitionValidityPassTest extends TestCase $this->addToAssertionCount(1); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - */ public function testInvalidTags() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $container->register('a', 'class')->addTag('foo', ['bar' => ['baz' => 'baz']]); $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\EnvParameterException - */ public function testDynamicPublicServiceName() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\EnvParameterException'); $container = new ContainerBuilder(); $env = $container->getParameterBag()->get('env(BAR)'); $container->register("foo.$env", 'class')->setPublic(true); @@ -88,11 +80,9 @@ class CheckDefinitionValidityPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\EnvParameterException - */ public function testDynamicPublicAliasName() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\EnvParameterException'); $container = new ContainerBuilder(); $env = $container->getParameterBag()->get('env(BAR)'); $container->setAlias("foo.$env", 'class')->setPublic(true); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php index 38717eaf1..c4f331b18 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/CheckExceptionOnInvalidReferenceBehaviorPassTest.php @@ -35,11 +35,9 @@ class CheckExceptionOnInvalidReferenceBehaviorPassTest extends TestCase $this->addToAssertionCount(1); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - */ public function testProcessThrowsExceptionOnInvalidReference() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); $container = new ContainerBuilder(); $container @@ -50,11 +48,9 @@ class CheckExceptionOnInvalidReferenceBehaviorPassTest extends TestCase $this->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - */ public function testProcessThrowsExceptionOnInvalidReferenceFromInlinedDefinition() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); $container = new ContainerBuilder(); $def = new Definition(); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/CheckReferenceValidityPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/CheckReferenceValidityPassTest.php index 22b6fd154..85a8a40f1 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/CheckReferenceValidityPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/CheckReferenceValidityPassTest.php @@ -18,11 +18,9 @@ use Symfony\Component\DependencyInjection\Reference; class CheckReferenceValidityPassTest extends TestCase { - /** - * @expectedException \RuntimeException - */ public function testProcessDetectsReferenceToAbstractDefinition() { + $this->expectException('RuntimeException'); $container = new ContainerBuilder(); $container->register('a')->setAbstract(true); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/DefinitionErrorExceptionPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/DefinitionErrorExceptionPassTest.php index ce6f0496e..273261976 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/DefinitionErrorExceptionPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/DefinitionErrorExceptionPassTest.php @@ -18,12 +18,10 @@ use Symfony\Component\DependencyInjection\Definition; class DefinitionErrorExceptionPassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Things went wrong! - */ public function testThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Things went wrong!'); $container = new ContainerBuilder(); $def = new Definition(); $def->addError('Things went wrong!'); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/InlineServiceDefinitionsPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/InlineServiceDefinitionsPassTest.php index 6e5c80a7d..d98db6406 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/InlineServiceDefinitionsPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/InlineServiceDefinitionsPassTest.php @@ -111,12 +111,10 @@ class InlineServiceDefinitionsPassTest extends TestCase $this->assertEquals(new Reference('bar'), $container->getDefinition('foo')->getArgument(0)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - * @expectedExceptionMessage Circular reference detected for service "bar", path: "bar -> foo -> bar". - */ public function testProcessThrowsOnNonSharedLoops() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); + $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> foo -> bar".'); $container = new ContainerBuilder(); $container ->register('foo') diff --git a/lib/symfony/dependency-injection/Tests/Compiler/IntegrationTest.php b/lib/symfony/dependency-injection/Tests/Compiler/IntegrationTest.php index 10c34aa48..348d1d7f5 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/IntegrationTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/IntegrationTest.php @@ -43,7 +43,7 @@ class IntegrationTest extends TestCase ->addArgument(new Reference('c')) ; - $b = $container + $container ->register('b', '\stdClass') ->addArgument(new Reference('c')) ->setPublic(false) diff --git a/lib/symfony/dependency-injection/Tests/Compiler/MergeExtensionConfigurationPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/MergeExtensionConfigurationPassTest.php index 1bef795f2..13692657b 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/MergeExtensionConfigurationPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/MergeExtensionConfigurationPassTest.php @@ -85,7 +85,7 @@ class MergeExtensionConfigurationPassTest extends TestCase $pass = new MergeExtensionConfigurationPass(); $pass->process($container); - $this->assertContains(new FileResource(__FILE__), $container->getResources(), '', false, false); + $this->assertContainsEquals(new FileResource(__FILE__), $container->getResources()); } public function testOverriddenEnvsAreMerged() @@ -102,12 +102,10 @@ class MergeExtensionConfigurationPassTest extends TestCase $this->assertSame(['BAZ' => 1, 'FOO' => 0], $container->getEnvCounters()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Using a cast in "env(int:FOO)" is incompatible with resolution at compile time in "Symfony\Component\DependencyInjection\Tests\Compiler\BarExtension". The logic in the extension should be moved to a compiler pass, or an env parameter with no cast should be used instead. - */ public function testProcessedEnvsAreIncompatibleWithResolve() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Using a cast in "env(int:FOO)" is incompatible with resolution at compile time in "Symfony\Component\DependencyInjection\Tests\Compiler\BarExtension". The logic in the extension should be moved to a compiler pass, or an env parameter with no cast should be used instead.'); $container = new ContainerBuilder(); $container->registerExtension(new BarExtension()); $container->prependExtensionConfig('bar', []); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php index 3d3fdf769..2c42ba0ce 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/RegisterEnvVarProcessorsPassTest.php @@ -53,12 +53,10 @@ class RegisterEnvVarProcessorsPassTest extends TestCase $this->assertFalse($container->has('container.env_var_processors_locator')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid type "foo" returned by "Symfony\Component\DependencyInjection\Tests\Compiler\BadProcessor::getProvidedTypes()", expected one of "array", "bool", "float", "int", "string". - */ public function testBadProcessor() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid type "foo" returned by "Symfony\Component\DependencyInjection\Tests\Compiler\BadProcessor::getProvidedTypes()", expected one of "array", "bool", "float", "int", "string".'); $container = new ContainerBuilder(); $container->register('foo', BadProcessor::class)->addTag('container.env_var_processor'); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/RegisterServiceSubscribersPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/RegisterServiceSubscribersPassTest.php index 0356c9713..a16bfc169 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/RegisterServiceSubscribersPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/RegisterServiceSubscribersPassTest.php @@ -28,12 +28,10 @@ require_once __DIR__.'/../Fixtures/includes/classes.php'; class RegisterServiceSubscribersPassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Service "foo" must implement interface "Symfony\Component\DependencyInjection\ServiceSubscriberInterface". - */ public function testInvalidClass() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Service "foo" must implement interface "Symfony\Component\DependencyInjection\ServiceSubscriberInterface".'); $container = new ContainerBuilder(); $container->register('foo', CustomDefinition::class) @@ -44,12 +42,10 @@ class RegisterServiceSubscribersPassTest extends TestCase (new ResolveServiceSubscribersPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The "container.service_subscriber" tag accepts only the "key" and "id" attributes, "bar" given for service "foo". - */ public function testInvalidAttributes() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "container.service_subscriber" tag accepts only the "key" and "id" attributes, "bar" given for service "foo".'); $container = new ContainerBuilder(); $container->register('foo', TestServiceSubscriber::class) @@ -118,12 +114,10 @@ class RegisterServiceSubscribersPassTest extends TestCase $this->assertEquals($expected, $container->getDefinition((string) $locator->getFactory()[0])->getArgument(0)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Service key "test" does not exist in the map returned by "Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber::getSubscribedServices()" for service "foo_service". - */ public function testExtraServiceSubscriber() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Service key "test" does not exist in the map returned by "Symfony\Component\DependencyInjection\Tests\Fixtures\TestServiceSubscriber::getSubscribedServices()" for service "foo_service".'); $container = new ContainerBuilder(); $container->register('foo_service', TestServiceSubscriber::class) ->setAutowired(true) diff --git a/lib/symfony/dependency-injection/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.php index f9c755c35..2f0a413ca 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/ReplaceAliasByActualDefinitionPassTest.php @@ -53,11 +53,9 @@ class ReplaceAliasByActualDefinitionPassTest extends TestCase $this->assertSame('b_alias', (string) $resolvedFactory[0]); } - /** - * @expectedException \InvalidArgumentException - */ public function testProcessWithInvalidAlias() { + $this->expectException('InvalidArgumentException'); $container = new ContainerBuilder(); $container->setAlias('a_alias', 'a'); $this->process($container); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/ResolveBindingsPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/ResolveBindingsPassTest.php index 7bbecf620..fd526caa9 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/ResolveBindingsPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/ResolveBindingsPassTest.php @@ -14,9 +14,11 @@ namespace Symfony\Component\DependencyInjection\Tests\Compiler; use PHPUnit\Framework\TestCase; use Symfony\Component\DependencyInjection\Argument\BoundArgument; use Symfony\Component\DependencyInjection\Compiler\AutowireRequiredMethodsPass; +use Symfony\Component\DependencyInjection\Compiler\DefinitionErrorExceptionPass; use Symfony\Component\DependencyInjection\Compiler\ResolveBindingsPass; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; +use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Tests\Fixtures\CaseSensitiveClass; use Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy; @@ -48,12 +50,10 @@ class ResolveBindingsPassTest extends TestCase $this->assertEquals([['setSensitiveClass', [new Reference('foo')]]], $definition->getMethodCalls()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Unused binding "$quz" in service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy". - */ public function testUnusedBinding() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Unused binding "$quz" in service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy".'); $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class); @@ -63,12 +63,11 @@ class ResolveBindingsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegexp Unused binding "$quz" in service [\s\S]+ Invalid service ".*\\ParentNotExists": class NotExists not found\. - */ public function testMissingParent() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Unused binding "\$quz" in service [\s\S]+/'); + $container = new ContainerBuilder(); $definition = $container->register(ParentNotExists::class, ParentNotExists::class); @@ -113,12 +112,10 @@ class ResolveBindingsPassTest extends TestCase $this->assertEquals([['setDefaultLocale', ['fr']]], $definition->getMethodCalls()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @exceptedExceptionMessage Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "setLogger()" does not exist. - */ public function testWithNonExistingSetterAndBinding() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "setLogger()" does not exist.'); $container = new ContainerBuilder(); $bindings = [ @@ -132,4 +129,25 @@ class ResolveBindingsPassTest extends TestCase $pass = new ResolveBindingsPass(); $pass->process($container); } + + public function testSyntheticServiceWithBind() + { + $container = new ContainerBuilder(); + $argument = new BoundArgument('bar'); + + $container->register('foo', 'stdClass') + ->addArgument(new Reference('synthetic.service')); + + $container->register('synthetic.service') + ->setSynthetic(true) + ->setBindings(['$apiKey' => $argument]); + + $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class) + ->setBindings(['$apiKey' => $argument]); + + (new ResolveBindingsPass())->process($container); + (new DefinitionErrorExceptionPass())->process($container); + + $this->assertSame([1 => 'bar'], $container->getDefinition(NamedArgumentsDummy::class)->getArguments()); + } } diff --git a/lib/symfony/dependency-injection/Tests/Compiler/ResolveChildDefinitionsPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/ResolveChildDefinitionsPassTest.php index 4eca8f707..eee4cf730 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/ResolveChildDefinitionsPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/ResolveChildDefinitionsPassTest.php @@ -390,7 +390,7 @@ class ResolveChildDefinitionsPassTest extends TestCase ->setBindings(['a' => '1', 'b' => '2']) ; - $child = $container->setDefinition('child', new ChildDefinition('parent')) + $container->setDefinition('child', new ChildDefinition('parent')) ->setBindings(['b' => 'B', 'c' => 'C']) ; @@ -432,12 +432,10 @@ class ResolveChildDefinitionsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - * @expectedExceptionMessageRegExp /^Circular reference detected for service "c", path: "c -> b -> a -> c"./ - */ public function testProcessDetectsChildDefinitionIndirectCircularReference() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); + $this->expectExceptionMessageRegExp('/^Circular reference detected for service "c", path: "c -> b -> a -> c"./'); $container = new ContainerBuilder(); $container->register('a'); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/ResolveClassPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/ResolveClassPassTest.php index 48df3843d..81e05fb28 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/ResolveClassPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/ResolveClassPassTest.php @@ -82,15 +82,13 @@ class ResolveClassPassTest extends TestCase $this->assertSame(self::class, $child->getClass()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Service definition "App\Foo\Child" has a parent but no class, and its name looks like a FQCN. Either the class is missing or you want to inherit it from the parent service. To resolve this ambiguity, please rename this service to a non-FQCN (e.g. using dots), or create the missing class. - */ public function testAmbiguousChildDefinition() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Service definition "App\Foo\Child" has a parent but no class, and its name looks like a FQCN. Either the class is missing or you want to inherit it from the parent service. To resolve this ambiguity, please rename this service to a non-FQCN (e.g. using dots), or create the missing class.'); $container = new ContainerBuilder(); - $parent = $container->register('App\Foo', null); - $child = $container->setDefinition('App\Foo\Child', new ChildDefinition('App\Foo')); + $container->register('App\Foo', null); + $container->setDefinition('App\Foo\Child', new ChildDefinition('App\Foo')); (new ResolveClassPass())->process($container); } diff --git a/lib/symfony/dependency-injection/Tests/Compiler/ResolveFactoryClassPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/ResolveFactoryClassPassTest.php index 3438fad06..b87fb3db9 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/ResolveFactoryClassPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/ResolveFactoryClassPassTest.php @@ -71,12 +71,10 @@ class ResolveFactoryClassPassTest extends TestCase $this->assertSame($factory, $container->getDefinition('factory')->getFactory()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The "factory" service is defined to be created by a factory, but is missing the factory class. Did you forget to define the factory or service class? - */ public function testNotAnyClassThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The "factory" service is defined to be created by a factory, but is missing the factory class. Did you forget to define the factory or service class?'); $container = new ContainerBuilder(); $factory = $container->register('factory'); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php index 26560b4ca..83be84bd0 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/ResolveInstanceofConditionalsPassTest.php @@ -172,12 +172,10 @@ class ResolveInstanceofConditionalsPassTest extends TestCase $this->assertFalse($def->isAutowired()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage "App\FakeInterface" is set as an "instanceof" conditional, but it does not exist. - */ public function testBadInterfaceThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('"App\FakeInterface" is set as an "instanceof" conditional, but it does not exist.'); $container = new ContainerBuilder(); $def = $container->register('normal_service', self::class); $def->setInstanceofConditionals([ @@ -200,12 +198,10 @@ class ResolveInstanceofConditionalsPassTest extends TestCase $this->assertTrue($container->hasDefinition('normal_service')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Autoconfigured instanceof for type "PHPUnit\Framework\TestCase" defines method calls but these are not supported and should be removed. - */ public function testProcessThrowsExceptionForAutoconfiguredCalls() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Autoconfigured instanceof for type "PHPUnit[\\\\_]Framework[\\\\_]TestCase" defines method calls but these are not supported and should be removed\./'); $container = new ContainerBuilder(); $container->registerForAutoconfiguration(parent::class) ->addMethodCall('setFoo'); @@ -213,12 +209,10 @@ class ResolveInstanceofConditionalsPassTest extends TestCase (new ResolveInstanceofConditionalsPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Autoconfigured instanceof for type "PHPUnit\Framework\TestCase" defines arguments but these are not supported and should be removed. - */ public function testProcessThrowsExceptionForArguments() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Autoconfigured instanceof for type "PHPUnit[\\\\_]Framework[\\\\_]TestCase" defines arguments but these are not supported and should be removed\./'); $container = new ContainerBuilder(); $container->registerForAutoconfiguration(parent::class) ->addArgument('bar'); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/ResolveNamedArgumentsPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/ResolveNamedArgumentsPassTest.php index e25d96f53..a10d226f1 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/ResolveNamedArgumentsPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/ResolveNamedArgumentsPassTest.php @@ -60,11 +60,9 @@ class ResolveNamedArgumentsPassTest extends TestCase $this->assertSame([0 => '123'], $definition->getArguments()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - */ public function testClassNull() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class); @@ -74,11 +72,9 @@ class ResolveNamedArgumentsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - */ public function testClassNotExist() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $definition = $container->register(NotExist::class, NotExist::class); @@ -88,11 +84,9 @@ class ResolveNamedArgumentsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - */ public function testClassNoConstructor() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); $container = new ContainerBuilder(); $definition = $container->register(NoConstructor::class, NoConstructor::class); @@ -102,12 +96,10 @@ class ResolveNamedArgumentsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "__construct()" has no argument named "$notFound". Check your service definition. - */ public function testArgumentNotFound() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\NamedArgumentsDummy": method "__construct()" has no argument named "$notFound". Check your service definition.'); $container = new ContainerBuilder(); $definition = $container->register(NamedArgumentsDummy::class, NamedArgumentsDummy::class); @@ -117,12 +109,10 @@ class ResolveNamedArgumentsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\TestDefinition1": method "Symfony\Component\DependencyInjection\Tests\Fixtures\FactoryDummyWithoutReturnTypes::createTestDefinition1()" has no argument named "$notFound". Check your service definition. - */ public function testCorrectMethodReportedInException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid service "Symfony\Component\DependencyInjection\Tests\Fixtures\TestDefinition1": method "Symfony\Component\DependencyInjection\Tests\Fixtures\FactoryDummyWithoutReturnTypes::createTestDefinition1()" has no argument named "$notFound". Check your service definition.'); $container = new ContainerBuilder(); $container->register(FactoryDummyWithoutReturnTypes::class, FactoryDummyWithoutReturnTypes::class); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/ResolveReferencesToAliasesPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/ResolveReferencesToAliasesPassTest.php index 55b47057b..2465bb7e3 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/ResolveReferencesToAliasesPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/ResolveReferencesToAliasesPassTest.php @@ -51,11 +51,9 @@ class ResolveReferencesToAliasesPassTest extends TestCase $this->assertEquals('foo', (string) $arguments[0]); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testAliasCircularReference() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $container = new ContainerBuilder(); $container->setAlias('bar', 'foo'); $container->setAlias('foo', 'bar'); diff --git a/lib/symfony/dependency-injection/Tests/Compiler/ServiceLocatorTagPassTest.php b/lib/symfony/dependency-injection/Tests/Compiler/ServiceLocatorTagPassTest.php index 27ee7db53..66af69b54 100644 --- a/lib/symfony/dependency-injection/Tests/Compiler/ServiceLocatorTagPassTest.php +++ b/lib/symfony/dependency-injection/Tests/Compiler/ServiceLocatorTagPassTest.php @@ -25,12 +25,10 @@ require_once __DIR__.'/../Fixtures/includes/classes.php'; class ServiceLocatorTagPassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid definition for service "foo": an array of references is expected as first argument when the "container.service_locator" tag is set. - */ public function testNoServices() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid definition for service "foo": an array of references is expected as first argument when the "container.service_locator" tag is set.'); $container = new ContainerBuilder(); $container->register('foo', ServiceLocator::class) @@ -40,12 +38,10 @@ class ServiceLocatorTagPassTest extends TestCase (new ServiceLocatorTagPass())->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid definition for service "foo": an array of references is expected as first argument when the "container.service_locator" tag is set, "string" found for key "0". - */ public function testInvalidServices() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid definition for service "foo": an array of references is expected as first argument when the "container.service_locator" tag is set, "string" found for key "0".'); $container = new ContainerBuilder(); $container->register('foo', ServiceLocator::class) @@ -118,6 +114,7 @@ class ServiceLocatorTagPassTest extends TestCase ->setArguments([[ 'bar' => new Reference('baz'), new Reference('bar'), + 16 => new Reference('baz'), ]]) ->addTag('container.service_locator') ; @@ -128,6 +125,7 @@ class ServiceLocatorTagPassTest extends TestCase $locator = $container->get('foo'); $this->assertSame(TestDefinition1::class, \get_class($locator('bar'))); + $this->assertSame(TestDefinition2::class, \get_class($locator(16))); } public function testBindingsAreCopied() diff --git a/lib/symfony/dependency-injection/Tests/Config/ContainerParametersResourceCheckerTest.php b/lib/symfony/dependency-injection/Tests/Config/ContainerParametersResourceCheckerTest.php index eb5fc5a99..51af451c1 100644 --- a/lib/symfony/dependency-injection/Tests/Config/ContainerParametersResourceCheckerTest.php +++ b/lib/symfony/dependency-injection/Tests/Config/ContainerParametersResourceCheckerTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\DependencyInjection\Tests\Config; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\Config\ResourceCheckerInterface; use Symfony\Component\DependencyInjection\Config\ContainerParametersResource; @@ -52,15 +53,15 @@ class ContainerParametersResourceCheckerTest extends TestCase public function isFreshProvider() { - yield 'not fresh on missing parameter' => [function (\PHPUnit_Framework_MockObject_MockObject $container) { + yield 'not fresh on missing parameter' => [function (MockObject $container) { $container->method('hasParameter')->with('locales')->willReturn(false); }, false]; - yield 'not fresh on different value' => [function (\PHPUnit_Framework_MockObject_MockObject $container) { + yield 'not fresh on different value' => [function (MockObject $container) { $container->method('getParameter')->with('locales')->willReturn(['nl', 'es']); }, false]; - yield 'fresh on every identical parameters' => [function (\PHPUnit_Framework_MockObject_MockObject $container) { + yield 'fresh on every identical parameters' => [function (MockObject $container) { $container->expects($this->exactly(2))->method('hasParameter')->willReturn(true); $container->expects($this->exactly(2))->method('getParameter') ->withConsecutive( diff --git a/lib/symfony/dependency-injection/Tests/ContainerBuilderTest.php b/lib/symfony/dependency-injection/Tests/ContainerBuilderTest.php index 46074a67a..f2666ef96 100644 --- a/lib/symfony/dependency-injection/Tests/ContainerBuilderTest.php +++ b/lib/symfony/dependency-injection/Tests/ContainerBuilderTest.php @@ -128,12 +128,10 @@ class ContainerBuilderTest extends TestCase $this->assertTrue($builder->has('bar'), '->has() returns true if a service exists'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage You have requested a non-existent service "foo". - */ public function testGetThrowsExceptionIfServiceDoesNotExist() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $this->expectExceptionMessage('You have requested a non-existent service "foo".'); $builder = new ContainerBuilder(); $builder->get('foo'); } @@ -145,11 +143,9 @@ class ContainerBuilderTest extends TestCase $this->assertNull($builder->get('foo', ContainerInterface::NULL_ON_INVALID_REFERENCE), '->get() returns null if the service does not exist and NULL_ON_INVALID_REFERENCE is passed as a second argument'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - */ public function testGetThrowsCircularReferenceExceptionIfServiceHasReferenceToItself() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); $builder = new ContainerBuilder(); $builder->register('baz', 'stdClass')->setArguments([new Reference('baz')]); $builder->get('baz'); @@ -168,7 +164,7 @@ class ContainerBuilderTest extends TestCase $builder = new ContainerBuilder(); $builder->register('foo', 'stdClass'); - $this->assertInternalType('object', $builder->get('foo'), '->get() returns the service definition associated with the id'); + $this->assertIsObject($builder->get('foo'), '->get() returns the service definition associated with the id'); } public function testGetReturnsRegisteredService() @@ -197,21 +193,21 @@ class ContainerBuilderTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException * @dataProvider provideBadId */ public function testBadAliasId($id) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $builder = new ContainerBuilder(); $builder->setAlias($id, 'foo'); } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException * @dataProvider provideBadId */ public function testBadDefinitionId($id) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $builder = new ContainerBuilder(); $builder->setDefinition($id, new Definition('Foo')); } @@ -228,12 +224,10 @@ class ContainerBuilderTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage You have requested a synthetic service ("foo"). The DIC does not know how to construct this service. - */ public function testGetUnsetLoadingServiceWhenCreateServiceThrowsAnException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('You have requested a synthetic service ("foo"). The DIC does not know how to construct this service.'); $builder = new ContainerBuilder(); $builder->register('foo', 'stdClass')->setSynthetic(true); @@ -512,11 +506,9 @@ class ContainerBuilderTest extends TestCase $this->assertEquals(0, $i); } - /** - * @expectedException \RuntimeException - */ public function testCreateSyntheticService() { + $this->expectException('RuntimeException'); $builder = new ContainerBuilder(); $builder->register('foo', 'Bar\FooClass')->setSynthetic(true); $builder->get('foo'); @@ -540,12 +532,10 @@ class ContainerBuilderTest extends TestCase $this->assertEquals($builder->get('foo'), $builder->resolveServices(new Expression('service("foo")')), '->resolveServices() resolves expressions'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Constructing service "foo" from a parent definition is not supported at build time. - */ public function testResolveServicesWithDecoratedDefinition() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Constructing service "foo" from a parent definition is not supported at build time.'); $builder = new ContainerBuilder(); $builder->setDefinition('grandpa', new Definition('stdClass')); $builder->setDefinition('parent', new ChildDefinition('grandpa')); @@ -621,12 +611,10 @@ class ContainerBuilderTest extends TestCase $this->assertSame(['AInterface' => $childDefA, 'BInterface' => $childDefB], $container->getAutoconfiguredInstanceof()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage "AInterface" has already been autoconfigured and merge() does not support merging autoconfiguration for the same class/interface. - */ public function testMergeThrowsExceptionForDuplicateAutomaticInstanceofDefinitions() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('"AInterface" has already been autoconfigured and merge() does not support merging autoconfiguration for the same class/interface.'); $container = new ContainerBuilder(); $config = new ContainerBuilder(); $container->registerForAutoconfiguration('AInterface'); @@ -662,7 +650,7 @@ class ContainerBuilderTest extends TestCase $container->resolveEnvPlaceholders('%dummy%', true); $container->resolveEnvPlaceholders('%dummy2%', true); - $this->assertInternalType('array', $container->resolveEnvPlaceholders('%dummy2%', true)); + $this->assertIsArray($container->resolveEnvPlaceholders('%dummy2%', true)); foreach ($dummyArray as $key => $value) { $this->assertArrayHasKey($key, $container->resolveEnvPlaceholders('%dummy2%', true)); @@ -728,12 +716,10 @@ class ContainerBuilderTest extends TestCase putenv('ARRAY'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage A string value must be composed of strings and/or numbers, but found parameter "env(json:ARRAY)" of type array inside string value "ABC %env(json:ARRAY)%". - */ public function testCompileWithArrayInStringResolveEnv() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('A string value must be composed of strings and/or numbers, but found parameter "env(json:ARRAY)" of type array inside string value "ABC %env(json:ARRAY)%".'); putenv('ARRAY={"foo":"bar"}'); $container = new ContainerBuilder(); @@ -743,12 +729,10 @@ class ContainerBuilderTest extends TestCase putenv('ARRAY'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\EnvNotFoundException - * @expectedExceptionMessage Environment variable not found: "FOO". - */ public function testCompileWithResolveMissingEnv() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\EnvNotFoundException'); + $this->expectExceptionMessage('Environment variable not found: "FOO".'); $container = new ContainerBuilder(); $container->setParameter('foo', '%env(FOO)%'); $container->compile(true); @@ -827,12 +811,10 @@ class ContainerBuilderTest extends TestCase $this->assertSame(['baz_bar'], array_keys($container->getDefinition('foo')->getArgument(1))); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException - * @expectedExceptionMessage Circular reference detected for parameter "env(resolve:DUMMY_ENV_VAR)" ("env(resolve:DUMMY_ENV_VAR)" > "env(resolve:DUMMY_ENV_VAR)"). - */ public function testCircularDynamicEnv() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException'); + $this->expectExceptionMessage('Circular reference detected for parameter "env(resolve:DUMMY_ENV_VAR)" ("env(resolve:DUMMY_ENV_VAR)" > "env(resolve:DUMMY_ENV_VAR)").'); putenv('DUMMY_ENV_VAR=some%foo%'); $container = new ContainerBuilder(); @@ -846,11 +828,9 @@ class ContainerBuilderTest extends TestCase } } - /** - * @expectedException \LogicException - */ public function testMergeLogicException() { + $this->expectException('LogicException'); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->compile(); @@ -1053,7 +1033,7 @@ class ContainerBuilderTest extends TestCase $container->registerExtension($extension = new \ProjectExtension()); $this->assertSame($container->getExtension('project'), $extension, '->registerExtension() registers an extension'); - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('LogicException'); + $this->expectException('LogicException'); $container->getExtension('no_registered'); } @@ -1100,11 +1080,9 @@ class ContainerBuilderTest extends TestCase $this->assertInstanceOf('BarClass', $container->get('bar_user')->bar); } - /** - * @expectedException \BadMethodCallException - */ public function testThrowsExceptionWhenSetServiceOnACompiledContainer() { + $this->expectException('BadMethodCallException'); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->register('a', 'stdClass')->setPublic(true); @@ -1131,11 +1109,9 @@ class ContainerBuilderTest extends TestCase $this->assertEquals($a, $container->get('a')); } - /** - * @expectedException \BadMethodCallException - */ public function testThrowsExceptionWhenSetDefinitionOnACompiledContainer() { + $this->expectException('BadMethodCallException'); $container = new ContainerBuilder(); $container->setResourceTracking(false); $container->compile(); @@ -1227,12 +1203,10 @@ class ContainerBuilderTest extends TestCase $this->assertNotSame($bar->foo, $barUser->foo); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - * @expectedExceptionMessage Circular reference detected for service "app.test_class", path: "app.test_class -> App\TestClass -> app.test_class". - */ public function testThrowsCircularExceptionForCircularAliases() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); + $this->expectExceptionMessage('Circular reference detected for service "app.test_class", path: "app.test_class -> App\TestClass -> app.test_class".'); $builder = new ContainerBuilder(); $builder->setAliases([ @@ -1285,63 +1259,53 @@ class ContainerBuilderTest extends TestCase $this->assertEquals(CaseSensitiveClass::class, $autoloadClass->getClass()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The definition for "DateTime" has no class attribute, and appears to reference a class or interface in the global namespace. - */ public function testNoClassFromGlobalNamespaceClassId() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The definition for "DateTime" has no class attribute, and appears to reference a class or interface in the global namespace.'); $container = new ContainerBuilder(); - $definition = $container->register(\DateTime::class); + $container->register(\DateTime::class); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The definition for "\DateTime" has no class attribute, and appears to reference a class or interface in the global namespace. - */ public function testNoClassFromGlobalNamespaceClassIdWithLeadingSlash() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The definition for "\DateTime" has no class attribute, and appears to reference a class or interface in the global namespace.'); $container = new ContainerBuilder(); $container->register('\\'.\DateTime::class); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The definition for "\Symfony\Component\DependencyInjection\Tests\FooClass" has no class attribute, and appears to reference a class or interface. Please specify the class attribute explicitly or remove the leading backslash by renaming the service to "Symfony\Component\DependencyInjection\Tests\FooClass" to get rid of this error. - */ public function testNoClassFromNamespaceClassIdWithLeadingSlash() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The definition for "\Symfony\Component\DependencyInjection\Tests\FooClass" has no class attribute, and appears to reference a class or interface. Please specify the class attribute explicitly or remove the leading backslash by renaming the service to "Symfony\Component\DependencyInjection\Tests\FooClass" to get rid of this error.'); $container = new ContainerBuilder(); $container->register('\\'.FooClass::class); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The definition for "123_abc" has no class. - */ public function testNoClassFromNonClassId() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The definition for "123_abc" has no class.'); $container = new ContainerBuilder(); - $definition = $container->register('123_abc'); + $container->register('123_abc'); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The definition for "\foo" has no class. - */ public function testNoClassFromNsSeparatorId() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The definition for "\foo" has no class.'); $container = new ContainerBuilder(); - $definition = $container->register('\\foo'); + $container->register('\\foo'); $container->compile(); } @@ -1423,6 +1387,13 @@ class ContainerBuilderTest extends TestCase $this->assertEquals((object) ['bar6' => (object) []], $foo6); $this->assertInstanceOf(\stdClass::class, $container->get('root')); + + $manager3 = $container->get('manager3'); + $listener3 = $container->get('listener3'); + $this->assertSame($manager3, $listener3->manager, 'Both should identically be the manager3 service'); + + $listener4 = $container->get('listener4'); + $this->assertInstanceOf('stdClass', $listener4); } public function provideAlmostCircular() diff --git a/lib/symfony/dependency-injection/Tests/ContainerTest.php b/lib/symfony/dependency-injection/Tests/ContainerTest.php index 5dbec886e..46527e09d 100644 --- a/lib/symfony/dependency-injection/Tests/ContainerTest.php +++ b/lib/symfony/dependency-injection/Tests/ContainerTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\DependencyInjection\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; @@ -157,7 +156,7 @@ class ContainerTest extends TestCase $sc = new ProjectServiceContainer(); $sc->set('foo', $obj = new \stdClass()); - $this->assertEquals(['service_container', 'internal', 'bar', 'foo_bar', 'foo.baz', 'circular', 'throw_exception', 'throws_exception_on_service_configuration', 'internal_dependency', 'foo'], $sc->getServiceIds(), '->getServiceIds() returns defined service ids by factory methods in the method map, followed by service ids defined by set()'); + $this->assertEquals(['service_container', 'internal', 'bar', 'foo_bar', 'foo.baz', 'circular', 'throw_exception', 'throws_exception_on_service_configuration', 'internal_dependency', 'alias', 'foo'], $sc->getServiceIds(), '->getServiceIds() returns defined service ids by factory methods in the method map, followed by service ids defined by set()'); } /** @@ -169,7 +168,7 @@ class ContainerTest extends TestCase $sc = new LegacyProjectServiceContainer(); $sc->set('foo', $obj = new \stdClass()); - $this->assertEquals(['internal', 'bar', 'foo_bar', 'foo.baz', 'circular', 'throw_exception', 'throws_exception_on_service_configuration', 'service_container', 'foo'], $sc->getServiceIds(), '->getServiceIds() returns defined service ids by getXXXService() methods, followed by service ids defined by set()'); + $this->assertEquals(['internal', 'bar', 'foo_bar', 'foo.baz', 'circular', 'throw_exception', 'throws_exception_on_service_configuration', 'service_container', 'alias', 'foo'], $sc->getServiceIds(), '->getServiceIds() returns defined service ids by getXXXService() methods, followed by service ids defined by set()'); } public function testSet() @@ -331,24 +330,20 @@ class ContainerTest extends TestCase } } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage The "request" service is synthetic, it needs to be set at boot time before it can be used. - */ public function testGetSyntheticServiceThrows() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $this->expectExceptionMessage('The "request" service is synthetic, it needs to be set at boot time before it can be used.'); require_once __DIR__.'/Fixtures/php/services9_compiled.php'; $container = new \ProjectServiceContainer(); $container->get('request'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage The "inlined" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead. - */ public function testGetRemovedServiceThrows() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $this->expectExceptionMessage('The "inlined" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.'); require_once __DIR__.'/Fixtures/php/services9_compiled.php'; $container = new \ProjectServiceContainer(); @@ -430,12 +425,10 @@ class ContainerTest extends TestCase $this->assertNull($c->get('bar', ContainerInterface::NULL_ON_INVALID_REFERENCE)); } - /** - * @expectedException \Exception - * @expectedExceptionMessage Something went terribly wrong! - */ public function testGetThrowsException() { + $this->expectException('Exception'); + $this->expectExceptionMessage('Something went terribly wrong!'); $c = new ProjectServiceContainer(); try { diff --git a/lib/symfony/dependency-injection/Tests/DefinitionDecoratorTest.php b/lib/symfony/dependency-injection/Tests/DefinitionDecoratorTest.php index ac58d3455..8d382f81f 100644 --- a/lib/symfony/dependency-injection/Tests/DefinitionDecoratorTest.php +++ b/lib/symfony/dependency-injection/Tests/DefinitionDecoratorTest.php @@ -92,11 +92,9 @@ class DefinitionDecoratorTest extends TestCase $this->assertEquals(['index_0' => 'foo'], $def->getArguments()); } - /** - * @expectedException \InvalidArgumentException - */ public function testReplaceArgumentShouldRequireIntegerIndex() { + $this->expectException('InvalidArgumentException'); $def = new DefinitionDecorator('foo'); $def->replaceArgument('0', 'foo'); @@ -117,11 +115,9 @@ class DefinitionDecoratorTest extends TestCase $this->assertEquals([0 => 'foo', 1 => 'bar', 'index_1' => 'baz'], $def->getArguments()); } - /** - * @expectedException \OutOfBoundsException - */ public function testGetArgumentShouldCheckBounds() { + $this->expectException('OutOfBoundsException'); $def = new DefinitionDecorator('foo'); $def->setArguments([0 => 'foo']); diff --git a/lib/symfony/dependency-injection/Tests/DefinitionTest.php b/lib/symfony/dependency-injection/Tests/DefinitionTest.php index 3581fe855..1f1cd380f 100644 --- a/lib/symfony/dependency-injection/Tests/DefinitionTest.php +++ b/lib/symfony/dependency-injection/Tests/DefinitionTest.php @@ -69,12 +69,8 @@ class DefinitionTest extends TestCase $def = new Definition('stdClass'); - if (method_exists($this, 'expectException')) { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage('The decorated service inner name for "foo" must be different than the service name itself.'); - } else { - $this->setExpectedException('InvalidArgumentException', 'The decorated service inner name for "foo" must be different than the service name itself.'); - } + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The decorated service inner name for "foo" must be different than the service name itself.'); $def->setDecoratedService('foo', 'foo'); } @@ -101,12 +97,10 @@ class DefinitionTest extends TestCase $this->assertEquals([['foo', ['foo']]], $def->getMethodCalls(), '->removeMethodCall() removes a method to call'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Method name cannot be empty. - */ public function testExceptionOnEmptyMethodCall() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Method name cannot be empty.'); $def = new Definition('stdClass'); $def->addMethodCall(''); } @@ -169,10 +163,10 @@ class DefinitionTest extends TestCase /** * @dataProvider invalidDeprecationMessageProvider - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException */ public function testSetDeprecatedWithInvalidDeprecationTemplate($message) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $def = new Definition('stdClass'); $def->setDeprecated(false, $message); } @@ -254,35 +248,29 @@ class DefinitionTest extends TestCase $this->assertSame(['foo', 'bar'], $def->getArguments()); } - /** - * @expectedException \OutOfBoundsException - */ public function testGetArgumentShouldCheckBounds() { + $this->expectException('OutOfBoundsException'); $def = new Definition('stdClass'); $def->addArgument('foo'); $def->getArgument(1); } - /** - * @expectedException \OutOfBoundsException - * @expectedExceptionMessage The index "1" is not in the range [0, 0]. - */ public function testReplaceArgumentShouldCheckBounds() { + $this->expectException('OutOfBoundsException'); + $this->expectExceptionMessage('The index "1" is not in the range [0, 0].'); $def = new Definition('stdClass'); $def->addArgument('foo'); $def->replaceArgument(1, 'bar'); } - /** - * @expectedException \OutOfBoundsException - * @expectedExceptionMessage Cannot replace arguments if none have been configured yet. - */ public function testReplaceArgumentWithoutExistingArgumentsShouldCheckBounds() { + $this->expectException('OutOfBoundsException'); + $this->expectExceptionMessage('Cannot replace arguments if none have been configured yet.'); $def = new Definition('stdClass'); $def->replaceArgument(0, 'bar'); } diff --git a/lib/symfony/dependency-injection/Tests/Dumper/PhpDumperTest.php b/lib/symfony/dependency-injection/Tests/Dumper/PhpDumperTest.php index 926933bb0..b2cbb3caf 100644 --- a/lib/symfony/dependency-injection/Tests/Dumper/PhpDumperTest.php +++ b/lib/symfony/dependency-injection/Tests/Dumper/PhpDumperTest.php @@ -150,10 +150,10 @@ class PhpDumperTest extends TestCase /** * @dataProvider provideInvalidParameters - * @expectedException \InvalidArgumentException */ public function testExportParameters($parameters) { + $this->expectException('InvalidArgumentException'); $container = new ContainerBuilder(new ParameterBag($parameters)); $container->compile(); $dumper = new PhpDumper($container); @@ -284,11 +284,11 @@ class PhpDumperTest extends TestCase /** * @dataProvider provideInvalidFactories - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Cannot dump definition */ public function testInvalidFactories($factory) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Cannot dump definition'); $container = new ContainerBuilder(); $def = new Definition('stdClass'); $def->setPublic(true); @@ -448,12 +448,10 @@ class PhpDumperTest extends TestCase $this->assertStringEqualsFile(__FILE__, $container->getParameter('random')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\EnvParameterException - * @expectedExceptionMessage Environment variables "FOO" are never used. Please, check your container's configuration. - */ public function testUnusedEnvParameter() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\EnvParameterException'); + $this->expectExceptionMessage('Environment variables "FOO" are never used. Please, check your container\'s configuration.'); $container = new ContainerBuilder(); $container->getParameter('env(FOO)'); $container->compile(); @@ -461,12 +459,10 @@ class PhpDumperTest extends TestCase $dumper->dump(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException - * @expectedExceptionMessage Circular reference detected for parameter "env(resolve:DUMMY_ENV_VAR)" ("env(resolve:DUMMY_ENV_VAR)" > "env(resolve:DUMMY_ENV_VAR)"). - */ public function testCircularDynamicEnv() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ParameterCircularReferenceException'); + $this->expectExceptionMessage('Circular reference detected for parameter "env(resolve:DUMMY_ENV_VAR)" ("env(resolve:DUMMY_ENV_VAR)" > "env(resolve:DUMMY_ENV_VAR)").'); $container = new ContainerBuilder(); $container->setParameter('foo', '%bar%'); $container->setParameter('bar', '%env(resolve:DUMMY_ENV_VAR)%'); @@ -546,12 +542,8 @@ class PhpDumperTest extends TestCase $dumper = new PhpDumper($container); $message = 'Circular reference detected for service "foo", path: "foo -> bar -> foo". Try running "composer require symfony/proxy-manager-bridge".'; - if (method_exists($this, 'expectException')) { - $this->expectException(ServiceCircularReferenceException::class); - $this->expectExceptionMessage($message); - } else { - $this->setExpectedException(ServiceCircularReferenceException::class, $message); - } + $this->expectException(ServiceCircularReferenceException::class); + $this->expectExceptionMessage($message); $dumper->dump(); } @@ -842,6 +834,13 @@ class PhpDumperTest extends TestCase $this->assertEquals((object) ['bar6' => (object) []], $foo6); $this->assertInstanceOf(\stdClass::class, $container->get('root')); + + $manager3 = $container->get('manager3'); + $listener3 = $container->get('listener3'); + $this->assertSame($manager3, $listener3->manager); + + $listener4 = $container->get('listener4'); + $this->assertInstanceOf('stdClass', $listener4); } public function provideAlmostCircular() @@ -887,7 +886,7 @@ class PhpDumperTest extends TestCase ->setPublic(true) ->addArgument($baz); - $passConfig = $container->getCompiler()->getPassConfig(); + $container->getCompiler()->getPassConfig(); $container->compile(); $dumper = new PhpDumper($container); @@ -979,7 +978,6 @@ class PhpDumperTest extends TestCase $container->compile(); $dumper = new PhpDumper($container); - $dump = $dumper->dump(); $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_adawson.php', $dumper->dump()); } @@ -1135,6 +1133,30 @@ class PhpDumperTest extends TestCase $this->assertTrue($container->has('foo')); $this->assertSame('some value', $container->get('foo')); } + + public function testAliasCanBeFoundInTheDumpedContainerWhenBothTheAliasAndTheServiceArePublic() + { + $container = new ContainerBuilder(); + + $container->register('foo', 'stdClass')->setPublic(true); + $container->setAlias('bar', 'foo')->setPublic(true); + + $container->compile(); + + // Bar is found in the compiled container + $service_ids = $container->getServiceIds(); + $this->assertContains('bar', $service_ids); + + $dumper = new PhpDumper($container); + $dump = $dumper->dump(['class' => 'Symfony_DI_PhpDumper_AliasesCanBeFoundInTheDumpedContainer']); + eval('?>'.$dump); + + $container = new \Symfony_DI_PhpDumper_AliasesCanBeFoundInTheDumpedContainer(); + + // Bar should still be found in the compiled container + $service_ids = $container->getServiceIds(); + $this->assertContains('bar', $service_ids); + } } class Rot13EnvVarProcessor implements EnvVarProcessorInterface diff --git a/lib/symfony/dependency-injection/Tests/EnvVarProcessorTest.php b/lib/symfony/dependency-injection/Tests/EnvVarProcessorTest.php index 972350467..2830d46a7 100644 --- a/lib/symfony/dependency-injection/Tests/EnvVarProcessorTest.php +++ b/lib/symfony/dependency-injection/Tests/EnvVarProcessorTest.php @@ -98,12 +98,12 @@ class EnvVarProcessorTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Non-numeric env var * @dataProvider invalidInts */ public function testGetEnvIntInvalid($value) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Non-numeric env var'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('int', 'foo', function ($name) use ($value) { @@ -148,12 +148,12 @@ class EnvVarProcessorTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Non-numeric env var * @dataProvider invalidFloats */ public function testGetEnvFloatInvalid($value) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Non-numeric env var'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('float', 'foo', function ($name) use ($value) { @@ -197,12 +197,12 @@ class EnvVarProcessorTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage undefined constant * @dataProvider invalidConsts */ public function testGetEnvConstInvalid($value) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('undefined constant'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('const', 'foo', function ($name) use ($value) { @@ -246,12 +246,10 @@ class EnvVarProcessorTest extends TestCase $this->assertSame([1], $result); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Syntax error - */ public function testGetEnvInvalidJson() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Syntax error'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('json', 'foo', function ($name) { @@ -262,12 +260,12 @@ class EnvVarProcessorTest extends TestCase } /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Invalid JSON env var * @dataProvider otherJsonValues */ public function testGetEnvJsonOther($value) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Invalid JSON env var'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('json', 'foo', function ($name) use ($value) { @@ -287,12 +285,10 @@ class EnvVarProcessorTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Unsupported env var prefix - */ public function testGetEnvUnknown() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Unsupported env var prefix'); $processor = new EnvVarProcessor(new Container()); $processor->getEnv('unknown', 'foo', function ($name) { diff --git a/lib/symfony/dependency-injection/Tests/Extension/ExtensionTest.php b/lib/symfony/dependency-injection/Tests/Extension/ExtensionTest.php index 3c912f2a1..9f35b4a41 100644 --- a/lib/symfony/dependency-injection/Tests/Extension/ExtensionTest.php +++ b/lib/symfony/dependency-injection/Tests/Extension/ExtensionTest.php @@ -34,12 +34,10 @@ class ExtensionTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The config array has no 'enabled' key. - */ public function testIsConfigEnabledOnNonEnableableConfig() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The config array has no \'enabled\' key.'); $extension = new EnableableExtension(); $extension->isConfigEnabled(new ContainerBuilder(), []); diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/Prototype/OtherDir/Component1/Dir2/Service2.php b/lib/symfony/dependency-injection/Tests/Fixtures/Prototype/OtherDir/Component1/Dir2/Service2.php index 44e7cacd2..ba103fce0 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/Prototype/OtherDir/Component1/Dir2/Service2.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/Prototype/OtherDir/Component1/Dir2/Service2.php @@ -4,5 +4,4 @@ namespace Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\OtherDi class Service2 { - } diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/Prototype/OtherDir/Component2/Dir2/Service5.php b/lib/symfony/dependency-injection/Tests/Fixtures/Prototype/OtherDir/Component2/Dir2/Service5.php index 691b42771..d2cff5b95 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/Prototype/OtherDir/Component2/Dir2/Service5.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/Prototype/OtherDir/Component2/Dir2/Service5.php @@ -4,5 +4,4 @@ namespace Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\OtherDi class Service5 { - } diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/StubbedTranslator.php b/lib/symfony/dependency-injection/Tests/Fixtures/StubbedTranslator.php index 8e1c2a6ce..eed18426a 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/StubbedTranslator.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/StubbedTranslator.php @@ -20,7 +20,6 @@ class StubbedTranslator { public function __construct(ContainerInterface $container) { - } public function addResource($format, $resource, $locale, $domain = null) diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/containers/container_almost_circular.php b/lib/symfony/dependency-injection/Tests/Fixtures/containers/container_almost_circular.php index df136cfa5..a1f885399 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/containers/container_almost_circular.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/containers/container_almost_circular.php @@ -2,7 +2,6 @@ use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Definition; -use Symfony\Component\DependencyInjection\Dumper\PhpDumper; use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Tests\Fixtures\FooForCircularWithAddCalls; @@ -102,6 +101,35 @@ $container->register('dispatcher2', 'stdClass')->setPublic($public) $container->register('subscriber2', 'stdClass')->setPublic(false) ->addArgument(new Reference('manager2')); +// doctrine-like event system with listener + +$container->register('manager3', 'stdClass') + ->setLazy(true) + ->setPublic(true) + ->addArgument(new Reference('connection3')); + +$container->register('connection3', 'stdClass') + ->setPublic($public) + ->setProperty('listener', [new Reference('listener3')]); + +$container->register('listener3', 'stdClass') + ->setPublic(true) + ->setProperty('manager', new Reference('manager3')); + +// doctrine-like event system with small differences + +$container->register('manager4', 'stdClass') + ->setLazy(true) + ->addArgument(new Reference('connection4')); + +$container->register('connection4', 'stdClass') + ->setPublic($public) + ->setProperty('listener', [new Reference('listener4')]); + +$container->register('listener4', 'stdClass') + ->setPublic(true) + ->addArgument(new Reference('manager4')); + // private service involved in a loop $container->register('foo6', 'stdClass') diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_constructor_without_arguments.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_constructor_without_arguments.php index 7495110dd..56f59d9dd 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_constructor_without_arguments.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_constructor_without_arguments.php @@ -18,7 +18,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\ConstructorWithoutArgumentsContainer { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_with_mandatory_constructor_arguments.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_with_mandatory_constructor_arguments.php index eb573f9ba..9e1abeb44 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_with_mandatory_constructor_arguments.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_with_mandatory_constructor_arguments.php @@ -18,7 +18,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\ConstructorWithMandatoryArgumentsContainer { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_with_optional_constructor_arguments.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_with_optional_constructor_arguments.php index d322f80a0..2fe30f22e 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_with_optional_constructor_arguments.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_with_optional_constructor_arguments.php @@ -18,7 +18,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\ConstructorWithOptionalArgumentsContainer { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_without_constructor.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_without_constructor.php index 68bc1ef8b..c630ad090 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_without_constructor.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/custom_container_class_without_constructor.php @@ -18,7 +18,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends \Symfony\Component\DependencyInjection\Tests\Fixtures\Container\NoConstructorContainer { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services1-1.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services1-1.php index ed085a5ef..3c0ced8e9 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services1-1.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services1-1.php @@ -18,7 +18,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class Container extends \Symfony\Component\DependencyInjection\Dump\AbstractContainer { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services1.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services1.php index 9733ba9c6..f7d49dd4d 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services1.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services1.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services10.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services10.php index 1b7443352..961282993 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services10.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services10.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services12.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services12.php index ba564b82f..0e8f581e8 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services12.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services12.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services13.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services13.php index 40ce06dec..52f5cf25f 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services13.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services13.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services19.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services19.php index 664f4dd90..6f6f60451 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services19.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services19.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services24.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services24.php index b277ddd1c..963118e20 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services24.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services24.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services26.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services26.php index 595d12ba6..95055207d 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services26.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services26.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class Symfony_DI_PhpDumper_Test_EnvParameters extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services33.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services33.php index d4019a50a..915d05373 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services33.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services33.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services8.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services8.php index cc78c196a..ce4815ef8 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services8.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services8.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services9.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services9.php index 0e09ec624..6dd0baabd 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services9.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services9.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services9_as_files.txt b/lib/symfony/dependency-injection/Tests/Fixtures/php/services9_as_files.txt index 2dc415ced..ab7024fa5 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services9_as_files.txt +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services9_as_files.txt @@ -277,7 +277,7 @@ class ProjectServiceContainer extends Container { private $buildParameters; private $containerDir; - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct(array $buildParameters = [], $containerDir = __DIR__) diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services9_compiled.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services9_compiled.php index 02e0680da..c9df13b2e 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services9_compiled.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services9_compiled.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_adawson.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_adawson.php index 7986897d3..f4364df7f 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_adawson.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_adawson.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_almost_circular_private.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_almost_circular_private.php index 5345aa3b3..775235db6 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_almost_circular_private.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_almost_circular_private.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class Symfony_DI_PhpDumper_Test_Almost_Circular_Private extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() @@ -39,9 +39,13 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Private extends Container 'level4' => 'getLevel4Service', 'level5' => 'getLevel5Service', 'level6' => 'getLevel6Service', + 'listener3' => 'getListener3Service', + 'listener4' => 'getListener4Service', 'logger' => 'getLoggerService', 'manager' => 'getManagerService', 'manager2' => 'getManager2Service', + 'manager3' => 'getManager3Service', + 'manager4' => 'getManager4Service', 'multiuse1' => 'getMultiuse1Service', 'root' => 'getRootService', 'subscriber' => 'getSubscriberService', @@ -53,6 +57,7 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Private extends Container 'level4' => true, 'level5' => true, 'level6' => true, + 'manager4' => true, 'multiuse1' => true, ]; @@ -69,6 +74,8 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Private extends Container 'bar6' => true, 'config' => true, 'config2' => true, + 'connection3' => true, + 'connection4' => true, 'dispatcher' => true, 'dispatcher2' => true, 'foo4' => true, @@ -81,6 +88,7 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Private extends Container 'level5' => true, 'level6' => true, 'logger2' => true, + 'manager4' => true, 'multiuse1' => true, 'subscriber2' => true, ]; @@ -272,6 +280,36 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Private extends Container return $instance; } + /** + * Gets the public 'listener3' shared service. + * + * @return \stdClass + */ + protected function getListener3Service() + { + $this->services['listener3'] = $instance = new \stdClass(); + + $instance->manager = ${($_ = isset($this->services['manager3']) ? $this->services['manager3'] : $this->getManager3Service()) && false ?: '_'}; + + return $instance; + } + + /** + * Gets the public 'listener4' shared service. + * + * @return \stdClass + */ + protected function getListener4Service() + { + $a = ${($_ = isset($this->services['manager4']) ? $this->services['manager4'] : $this->getManager4Service()) && false ?: '_'}; + + if (isset($this->services['listener4'])) { + return $this->services['listener4']; + } + + return $this->services['listener4'] = new \stdClass($a); + } + /** * Gets the public 'logger' shared service. * @@ -324,6 +362,24 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Private extends Container return $this->services['manager2'] = new \stdClass($a); } + /** + * Gets the public 'manager3' shared service. + * + * @return \stdClass + */ + protected function getManager3Service($lazyLoad = true) + { + $a = ${($_ = isset($this->services['listener3']) ? $this->services['listener3'] : $this->getListener3Service()) && false ?: '_'}; + + if (isset($this->services['manager3'])) { + return $this->services['manager3']; + } + $b = new \stdClass(); + $b->listener = [0 => $a]; + + return $this->services['manager3'] = new \stdClass($b); + } + /** * Gets the public 'root' shared service. * @@ -430,6 +486,22 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Private extends Container return $instance; } + /** + * Gets the private 'manager4' shared service. + * + * @return \stdClass + */ + protected function getManager4Service($lazyLoad = true) + { + $a = new \stdClass(); + + $this->services['manager4'] = $instance = new \stdClass($a); + + $a->listener = [0 => ${($_ = isset($this->services['listener4']) ? $this->services['listener4'] : $this->getListener4Service()) && false ?: '_'}]; + + return $instance; + } + /** * Gets the private 'multiuse1' shared service. * diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_almost_circular_public.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_almost_circular_public.php index b569b335f..d3bab9128 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_almost_circular_public.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_almost_circular_public.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class Symfony_DI_PhpDumper_Test_Almost_Circular_Public extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() @@ -30,6 +30,8 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Public extends Container 'baz6' => 'getBaz6Service', 'connection' => 'getConnectionService', 'connection2' => 'getConnection2Service', + 'connection3' => 'getConnection3Service', + 'connection4' => 'getConnection4Service', 'dispatcher' => 'getDispatcherService', 'dispatcher2' => 'getDispatcher2Service', 'foo' => 'getFooService', @@ -46,9 +48,13 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Public extends Container 'level4' => 'getLevel4Service', 'level5' => 'getLevel5Service', 'level6' => 'getLevel6Service', + 'listener3' => 'getListener3Service', + 'listener4' => 'getListener4Service', 'logger' => 'getLoggerService', 'manager' => 'getManagerService', 'manager2' => 'getManager2Service', + 'manager3' => 'getManager3Service', + 'manager4' => 'getManager4Service', 'multiuse1' => 'getMultiuse1Service', 'root' => 'getRootService', 'subscriber' => 'getSubscriberService', @@ -60,6 +66,7 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Public extends Container 'level4' => true, 'level5' => true, 'level6' => true, + 'manager4' => true, 'multiuse1' => true, ]; @@ -81,6 +88,7 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Public extends Container 'level5' => true, 'level6' => true, 'logger2' => true, + 'manager4' => true, 'multiuse1' => true, 'subscriber2' => true, ]; @@ -212,6 +220,34 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Public extends Container return $instance; } + /** + * Gets the public 'connection3' shared service. + * + * @return \stdClass + */ + protected function getConnection3Service() + { + $this->services['connection3'] = $instance = new \stdClass(); + + $instance->listener = [0 => ${($_ = isset($this->services['listener3']) ? $this->services['listener3'] : $this->getListener3Service()) && false ?: '_'}]; + + return $instance; + } + + /** + * Gets the public 'connection4' shared service. + * + * @return \stdClass + */ + protected function getConnection4Service() + { + $this->services['connection4'] = $instance = new \stdClass(); + + $instance->listener = [0 => ${($_ = isset($this->services['listener4']) ? $this->services['listener4'] : $this->getListener4Service()) && false ?: '_'}]; + + return $instance; + } + /** * Gets the public 'dispatcher' shared service. * @@ -372,6 +408,36 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Public extends Container return $instance; } + /** + * Gets the public 'listener3' shared service. + * + * @return \stdClass + */ + protected function getListener3Service() + { + $this->services['listener3'] = $instance = new \stdClass(); + + $instance->manager = ${($_ = isset($this->services['manager3']) ? $this->services['manager3'] : $this->getManager3Service()) && false ?: '_'}; + + return $instance; + } + + /** + * Gets the public 'listener4' shared service. + * + * @return \stdClass + */ + protected function getListener4Service() + { + $a = ${($_ = isset($this->services['manager4']) ? $this->services['manager4'] : $this->getManager4Service()) && false ?: '_'}; + + if (isset($this->services['listener4'])) { + return $this->services['listener4']; + } + + return $this->services['listener4'] = new \stdClass($a); + } + /** * Gets the public 'logger' shared service. * @@ -424,6 +490,22 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Public extends Container return $this->services['manager2'] = new \stdClass($a); } + /** + * Gets the public 'manager3' shared service. + * + * @return \stdClass + */ + protected function getManager3Service($lazyLoad = true) + { + $a = ${($_ = isset($this->services['connection3']) ? $this->services['connection3'] : $this->getConnection3Service()) && false ?: '_'}; + + if (isset($this->services['manager3'])) { + return $this->services['manager3']; + } + + return $this->services['manager3'] = new \stdClass($a); + } + /** * Gets the public 'root' shared service. * @@ -530,6 +612,22 @@ class Symfony_DI_PhpDumper_Test_Almost_Circular_Public extends Container return $instance; } + /** + * Gets the private 'manager4' shared service. + * + * @return \stdClass + */ + protected function getManager4Service($lazyLoad = true) + { + $a = ${($_ = isset($this->services['connection4']) ? $this->services['connection4'] : $this->getConnection4Service()) && false ?: '_'}; + + if (isset($this->services['manager4'])) { + return $this->services['manager4']; + } + + return $this->services['manager4'] = new \stdClass($a); + } + /** * Gets the private 'multiuse1' shared service. * diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_array_params.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_array_params.php index be59456b0..dd1ca0a61 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_array_params.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_array_params.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_base64_env.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_base64_env.php index 8582c3e2d..709a3c4f8 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_base64_env.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_base64_env.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class Symfony_DI_PhpDumper_Test_Base64Parameters extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_dedup_lazy_proxy.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_dedup_lazy_proxy.php index ec3c8028b..096b3b396 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_dedup_lazy_proxy.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_dedup_lazy_proxy.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_deep_graph.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_deep_graph.php index 4158fc628..0e3eed27f 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_deep_graph.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_deep_graph.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class Symfony_DI_PhpDumper_Test_Deep_Graph extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_env_in_id.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_env_in_id.php index ad76566b1..e0e4827df 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_env_in_id.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_env_in_id.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_inline_requires.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_inline_requires.php index 59582d9eb..841878836 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_inline_requires.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_inline_requires.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_inline_self_ref.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_inline_self_ref.php index 271aeb668..906b0cdc7 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_inline_self_ref.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_inline_self_ref.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class Symfony_DI_PhpDumper_Test_Inline_Self_Ref extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_legacy_privates.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_legacy_privates.php index 30dd2c9ba..9a0606173 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_legacy_privates.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_legacy_privates.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class Symfony_DI_PhpDumper_Test_Legacy_Privates extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_locator.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_locator.php index 4969b2db0..3826d5a6e 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_locator.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_locator.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_non_shared_lazy.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_non_shared_lazy.php index b56063a18..4cea5d2d9 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_non_shared_lazy.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_non_shared_lazy.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_private_frozen.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_private_frozen.php index da1d716c5..95995dec6 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_private_frozen.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_private_frozen.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_private_in_expression.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_private_in_expression.php index c7fb579b0..56d73c255 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_private_in_expression.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_private_in_expression.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_rot13_env.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_rot13_env.php index 8d1465c44..a7ad1f1c6 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_rot13_env.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_rot13_env.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class Symfony_DI_PhpDumper_Test_Rot13Parameters extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_subscriber.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_subscriber.php index dbb51eab3..ca89e01cc 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_subscriber.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_subscriber.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_tsantos.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_tsantos.php index b14cdebb9..b314feff7 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_tsantos.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_tsantos.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class ProjectServiceContainer extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_uninitialized_ref.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_uninitialized_ref.php index 7a24f72c5..a338c9d52 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_uninitialized_ref.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_uninitialized_ref.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class Symfony_DI_PhpDumper_Test_Uninitialized_Reference extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_unsupported_characters.php b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_unsupported_characters.php index a4c841cab..9e7e817df 100644 --- a/lib/symfony/dependency-injection/Tests/Fixtures/php/services_unsupported_characters.php +++ b/lib/symfony/dependency-injection/Tests/Fixtures/php/services_unsupported_characters.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; */ class Symfony_DI_PhpDumper_Test_Unsupported_Characters extends Container { - private $parameters; + private $parameters = []; private $targetDirs = []; public function __construct() diff --git a/lib/symfony/dependency-injection/Tests/LazyProxy/Instantiator/RealServiceInstantiatorTest.php b/lib/symfony/dependency-injection/Tests/LazyProxy/Instantiator/RealServiceInstantiatorTest.php index f93965f46..7f757297b 100644 --- a/lib/symfony/dependency-injection/Tests/LazyProxy/Instantiator/RealServiceInstantiatorTest.php +++ b/lib/symfony/dependency-injection/Tests/LazyProxy/Instantiator/RealServiceInstantiatorTest.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator; /** - * Tests for {@see \Symfony\Component\DependencyInjection\Instantiator\RealServiceInstantiator}. + * Tests for {@see \Symfony\Component\DependencyInjection\LazyProxy\Instantiator\RealServiceInstantiator}. * * @author Marco Pivetta */ diff --git a/lib/symfony/dependency-injection/Tests/LazyProxy/PhpDumper/NullDumperTest.php b/lib/symfony/dependency-injection/Tests/LazyProxy/PhpDumper/NullDumperTest.php index b1b9b399c..5ae149324 100644 --- a/lib/symfony/dependency-injection/Tests/LazyProxy/PhpDumper/NullDumperTest.php +++ b/lib/symfony/dependency-injection/Tests/LazyProxy/PhpDumper/NullDumperTest.php @@ -16,7 +16,7 @@ use Symfony\Component\DependencyInjection\Definition; use Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper; /** - * Tests for {@see \Symfony\Component\DependencyInjection\PhpDumper\NullDumper}. + * Tests for {@see \Symfony\Component\DependencyInjection\LazyProxy\PhpDumper\NullDumper}. * * @author Marco Pivetta */ diff --git a/lib/symfony/dependency-injection/Tests/Loader/DirectoryLoaderTest.php b/lib/symfony/dependency-injection/Tests/Loader/DirectoryLoaderTest.php index c7c303b68..b4f969a0e 100644 --- a/lib/symfony/dependency-injection/Tests/Loader/DirectoryLoaderTest.php +++ b/lib/symfony/dependency-injection/Tests/Loader/DirectoryLoaderTest.php @@ -58,12 +58,10 @@ class DirectoryLoaderTest extends TestCase $this->assertEquals(['ini' => 'ini', 'yaml' => 'yaml'], $this->container->getParameterBag()->all(), '->load() takes a single file that imports a directory'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The file "foo" does not exist (in: - */ public function testExceptionIsRaisedWhenDirectoryDoesNotExist() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The file "foo" does not exist (in:'); $this->loader->load('foo/'); } diff --git a/lib/symfony/dependency-injection/Tests/Loader/FileLoaderTest.php b/lib/symfony/dependency-injection/Tests/Loader/FileLoaderTest.php index 065acdf1b..ffe58a67e 100644 --- a/lib/symfony/dependency-injection/Tests/Loader/FileLoaderTest.php +++ b/lib/symfony/dependency-injection/Tests/Loader/FileLoaderTest.php @@ -178,18 +178,16 @@ class FileLoaderTest extends TestCase $this->assertTrue($container->has(MissingParent::class)); - $this->assertSame( - ['While discovering services from namespace "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\", an error was thrown when processing the class "Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\MissingParent": "Class Symfony\Component\DependencyInjection\Tests\Fixtures\Prototype\BadClasses\MissingClass not found".'], - $container->getDefinition(MissingParent::class)->getErrors() + $this->assertRegExp( + '{Class "?Symfony\\\\Component\\\\DependencyInjection\\\\Tests\\\\Fixtures\\\\Prototype\\\\BadClasses\\\\MissingClass"? not found}', + $container->getDefinition(MissingParent::class)->getErrors()[0] ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Expected to find class "Symfony\\Component\\DependencyInjection\\Tests\\Fixtures\\Prototype\\Bar" in file ".+" while importing services from resource "Prototype\/Sub\/\*", but it was not found\! Check the namespace prefix used with the resource/ - */ public function testRegisterClassesWithBadPrefix() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Expected to find class "Symfony\\\Component\\\DependencyInjection\\\Tests\\\Fixtures\\\Prototype\\\Bar" in file ".+" while importing services from resource "Prototype\/Sub\/\*", but it was not found\! Check the namespace prefix used with the resource/'); $container = new ContainerBuilder(); $loader = new TestFileLoader($container, new FileLocator(self::$fixturesPath.'/Fixtures')); diff --git a/lib/symfony/dependency-injection/Tests/Loader/IniFileLoaderTest.php b/lib/symfony/dependency-injection/Tests/Loader/IniFileLoaderTest.php index 1d7d3a93e..6f02b9ff6 100644 --- a/lib/symfony/dependency-injection/Tests/Loader/IniFileLoaderTest.php +++ b/lib/symfony/dependency-injection/Tests/Loader/IniFileLoaderTest.php @@ -95,30 +95,24 @@ class IniFileLoaderTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The file "foo.ini" does not exist (in: - */ public function testExceptionIsRaisedWhenIniFileDoesNotExist() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The file "foo.ini" does not exist (in:'); $this->loader->load('foo.ini'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The "nonvalid.ini" file is not valid. - */ public function testExceptionIsRaisedWhenIniFileCannotBeParsed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "nonvalid.ini" file is not valid.'); @$this->loader->load('nonvalid.ini'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The "almostvalid.ini" file is not valid. - */ public function testExceptionIsRaisedWhenIniFileIsAlmostValid() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The "almostvalid.ini" file is not valid.'); @$this->loader->load('almostvalid.ini'); } diff --git a/lib/symfony/dependency-injection/Tests/Loader/PhpFileLoaderTest.php b/lib/symfony/dependency-injection/Tests/Loader/PhpFileLoaderTest.php index 4f7c16890..e1812305e 100644 --- a/lib/symfony/dependency-injection/Tests/Loader/PhpFileLoaderTest.php +++ b/lib/symfony/dependency-injection/Tests/Loader/PhpFileLoaderTest.php @@ -77,12 +77,10 @@ class PhpFileLoaderTest extends TestCase } } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The service "child_service" cannot have a "parent" and also have "autoconfigure". Try disabling autoconfiguration for the service. - */ public function testAutoConfigureAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The service "child_service" cannot have a "parent" and also have "autoconfigure". Try disabling autoconfiguration for the service.'); $fixtures = realpath(__DIR__.'/../Fixtures'); $container = new ContainerBuilder(); $loader = new PhpFileLoader($container, new FileLocator()); @@ -90,12 +88,10 @@ class PhpFileLoaderTest extends TestCase $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid factory "factory:method": the `service:method` notation is not available when using PHP-based DI configuration. Use "[ref('factory'), 'method']" instead. - */ public function testFactoryShortNotationNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid factory "factory:method": the `service:method` notation is not available when using PHP-based DI configuration. Use "[ref(\'factory\'), \'method\']" instead.'); $fixtures = realpath(__DIR__.'/../Fixtures'); $container = new ContainerBuilder(); $loader = new PhpFileLoader($container, new FileLocator()); diff --git a/lib/symfony/dependency-injection/Tests/Loader/XmlFileLoaderTest.php b/lib/symfony/dependency-injection/Tests/Loader/XmlFileLoaderTest.php index 03376a641..2b963968d 100644 --- a/lib/symfony/dependency-injection/Tests/Loader/XmlFileLoaderTest.php +++ b/lib/symfony/dependency-injection/Tests/Loader/XmlFileLoaderTest.php @@ -325,22 +325,18 @@ class XmlFileLoaderTest extends TestCase } } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - */ public function testParseTagsWithoutNameThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('tag_without_name.xml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /The tag name for service ".+" in .* must be a non-empty string/ - */ public function testParseTagWithEmptyNameThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The tag name for service ".+" in .* must be a non-empty string/'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('tag_with_empty_name.xml'); @@ -442,7 +438,7 @@ class XmlFileLoaderTest extends TestCase $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); - $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); + $this->assertStringContainsString('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } // non-registered extension @@ -482,7 +478,7 @@ class XmlFileLoaderTest extends TestCase $e = $e->getPrevious(); $this->assertInstanceOf('InvalidArgumentException', $e, '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); - $this->assertContains('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); + $this->assertStringContainsString('The attribute \'bar\' is not allowed', $e->getMessage(), '->load() throws an InvalidArgumentException if the configuration does not validate the XSD'); } } @@ -730,36 +726,30 @@ class XmlFileLoaderTest extends TestCase $this->assertSame(['foo' => [[]], 'bar' => [[]]], $definition->getTags()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The service "child_service" cannot use the "parent" option in the same file where "instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file. - */ public function testInstanceOfAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The service "child_service" cannot use the "parent" option in the same file where "instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file.'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_instanceof_with_parent.xml'); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting autoconfigure="false" for the service. - */ public function testAutoConfigureAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting autoconfigure="false" for the service.'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_autoconfigure_with_parent.xml'); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Attribute "autowire" on service "child_service" cannot be inherited from "defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly. - */ public function testDefaultsAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Attribute "autowire" on service "child_service" cannot be inherited from "defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly.'); $container = new ContainerBuilder(); $loader = new XmlFileLoader($container, new FileLocator(self::$fixturesPath.'/xml')); $loader->load('services_defaults_with_parent.xml'); @@ -818,7 +808,6 @@ class XmlFileLoaderTest extends TestCase $container->compile(); $dumper = new PhpDumper($container); - $dump = $dumper->dump(); $this->assertStringEqualsFile(self::$fixturesPath.'/php/services_tsantos.php', $dumper->dump()); } diff --git a/lib/symfony/dependency-injection/Tests/Loader/YamlFileLoaderTest.php b/lib/symfony/dependency-injection/Tests/Loader/YamlFileLoaderTest.php index 05521bf78..1d187848b 100644 --- a/lib/symfony/dependency-injection/Tests/Loader/YamlFileLoaderTest.php +++ b/lib/symfony/dependency-injection/Tests/Loader/YamlFileLoaderTest.php @@ -42,12 +42,10 @@ class YamlFileLoaderTest extends TestCase require_once self::$fixturesPath.'/includes/ProjectExtension.php'; } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /The file ".+" does not exist./ - */ public function testLoadUnExistFile() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The file ".+" does not exist./'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/ini')); $r = new \ReflectionObject($loader); $m = $r->getMethod('loadFile'); @@ -56,12 +54,10 @@ class YamlFileLoaderTest extends TestCase $m->invoke($loader, 'foo.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /The file ".+" does not contain valid YAML./ - */ public function testLoadInvalidYamlFile() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The file ".+" does not contain valid YAML./'); $path = self::$fixturesPath.'/ini'; $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator($path)); $r = new \ReflectionObject($loader); @@ -73,10 +69,10 @@ class YamlFileLoaderTest extends TestCase /** * @dataProvider provideInvalidFiles - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException */ public function testLoadInvalidFile($file) { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load($file.'.yml'); @@ -301,40 +297,32 @@ class YamlFileLoaderTest extends TestCase $this->assertEquals(['manager' => [['alias' => 'user']]], $definition->getTags()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /The tag name for service ".+" in .+ must be a non-empty string/ - */ public function testTagWithEmptyNameThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The tag name for service ".+" in .+ must be a non-empty string/'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('tag_name_empty_string.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageREgExp /The tag name for service "\.+" must be a non-empty string/ - */ public function testTagWithNonStringNameThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The tag name for service ".+" in .+ must be a non-empty string/'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('tag_name_no_string.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - */ public function testTypesNotArray() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('bad_types1.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - */ public function testTypeNotString() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('bad_types2.yml'); } @@ -430,12 +418,10 @@ class YamlFileLoaderTest extends TestCase $this->assertFalse($container->getDefinition(Prototype\OtherDir\Component2\Dir2\Service5::class)->hasTag('foo')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /A "resource" attribute must be set when the "namespace" attribute is set for service ".+" in .+/ - */ public function testPrototypeWithNamespaceAndNoResource() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/A "resource" attribute must be set when the "namespace" attribute is set for service ".+" in .+/'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services_prototype_namespace_without_resource.yml'); @@ -506,58 +492,48 @@ class YamlFileLoaderTest extends TestCase $this->assertSame(['foo' => [[]], 'bar' => [[]]], $definition->getTags()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The service "child_service" cannot use the "parent" option in the same file where "_instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file. - */ public function testInstanceOfAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The service "child_service" cannot use the "parent" option in the same file where "_instanceof" configuration is defined as using both is not supported. Move your child definitions to a separate file.'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services_instanceof_with_parent.yml'); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting "autoconfigure: false" for the service. - */ public function testAutoConfigureAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The service "child_service" cannot have a "parent" and also have "autoconfigure". Try setting "autoconfigure: false" for the service.'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services_autoconfigure_with_parent.yml'); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Attribute "autowire" on service "child_service" cannot be inherited from "_defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly. - */ public function testDefaultsAndChildDefinitionNotAllowed() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Attribute "autowire" on service "child_service" cannot be inherited from "_defaults" when a "parent" is set. Move your child definitions to a separate file or define this attribute explicitly.'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services_defaults_with_parent.yml'); $container->compile(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage The value of the "decorates" option for the "bar" service must be the id of the service without the "@" prefix (replace "@foo" with "foo"). - */ public function testDecoratedServicesWithWrongSyntaxThrowsException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The value of the "decorates" option for the "bar" service must be the id of the service without the "@" prefix (replace "@foo" with "foo").'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('bad_decorates.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Parameter "tags" must be an array for service "Foo\\Bar" in .+services31_invalid_tags\.yml\. Check your YAML syntax./ - */ public function testInvalidTagsWithDefaults() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Parameter "tags" must be an array for service "Foo\\\Bar" in .+services31_invalid_tags\.yml\. Check your YAML syntax./'); $loader = new YamlFileLoader(new ContainerBuilder(), new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('services31_invalid_tags.yml'); } @@ -596,7 +572,7 @@ class YamlFileLoaderTest extends TestCase // Anonymous service in a callable $factory = $definition->getFactory(); - $this->assertInternalType('array', $factory); + $this->assertIsArray($factory); $this->assertInstanceOf(Reference::class, $factory[0]); $this->assertTrue($container->has((string) $factory[0])); $this->assertRegExp('/^\d+_Quz~[._A-Za-z0-9]{7}$/', (string) $factory[0]); @@ -646,23 +622,19 @@ class YamlFileLoaderTest extends TestCase $this->assertFalse($container->has('Bar')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Creating an alias using the tag "!service" is not allowed in ".+anonymous_services_alias\.yml"\./ - */ public function testAnonymousServicesWithAliases() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Creating an alias using the tag "!service" is not allowed in ".+anonymous_services_alias\.yml"\./'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('anonymous_services_alias.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Using an anonymous service in a parameter is not allowed in ".+anonymous_services_in_parameters\.yml"\./ - */ public function testAnonymousServicesInParameters() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Using an anonymous service in a parameter is not allowed in ".+anonymous_services_in_parameters\.yml"\./'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('anonymous_services_in_parameters.yml'); @@ -678,23 +650,19 @@ class YamlFileLoaderTest extends TestCase $this->assertFalse($container->getDefinition('override_defaults_settings_to_false')->isAutoconfigured()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Service "_defaults" key must be an array, "NULL" given in ".+bad_empty_defaults\.yml"\./ - */ public function testEmptyDefaultsThrowsClearException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Service "_defaults" key must be an array, "NULL" given in ".+bad_empty_defaults\.yml"\./'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('bad_empty_defaults.yml'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessageRegExp /Service "_instanceof" key must be an array, "NULL" given in ".+bad_empty_instanceof\.yml"\./ - */ public function testEmptyInstanceofThrowsClearException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/Service "_instanceof" key must be an array, "NULL" given in ".+bad_empty_instanceof\.yml"\./'); $container = new ContainerBuilder(); $loader = new YamlFileLoader($container, new FileLocator(self::$fixturesPath.'/yaml')); $loader->load('bad_empty_instanceof.yml'); diff --git a/lib/symfony/dependency-injection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php b/lib/symfony/dependency-injection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php index e7c88d2bb..4fcb2c840 100644 --- a/lib/symfony/dependency-injection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php +++ b/lib/symfony/dependency-injection/Tests/ParameterBag/EnvPlaceholderParameterBagTest.php @@ -16,11 +16,9 @@ use Symfony\Component\DependencyInjection\ParameterBag\EnvPlaceholderParameterBa class EnvPlaceholderParameterBagTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - */ public function testGetThrowsInvalidArgumentExceptionIfEnvNameContainsNonWordCharacters() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); $bag = new EnvPlaceholderParameterBag(); $bag->get('env(%foo%)'); } @@ -42,8 +40,8 @@ class EnvPlaceholderParameterBagTest extends TestCase $placeholder = array_values($placeholderForVariable)[0]; $this->assertCount(1, $placeholderForVariable); - $this->assertInternalType('string', $placeholder); - $this->assertContains($envVariableName, $placeholder); + $this->assertIsString($placeholder); + $this->assertStringContainsString($envVariableName, $placeholder); } public function testMergeWhereFirstBagIsEmptyWillWork() @@ -65,8 +63,8 @@ class EnvPlaceholderParameterBagTest extends TestCase $placeholder = array_values($placeholderForVariable)[0]; $this->assertCount(1, $placeholderForVariable); - $this->assertInternalType('string', $placeholder); - $this->assertContains($envVariableName, $placeholder); + $this->assertIsString($placeholder); + $this->assertStringContainsString($envVariableName, $placeholder); } public function testMergeWherePlaceholderOnlyExistsInSecond() @@ -129,12 +127,10 @@ class EnvPlaceholderParameterBagTest extends TestCase $this->assertNull($bag->all()['env(NULL_VAR)']); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The default value of env parameter "ARRAY_VAR" must be scalar or null, array given. - */ public function testResolveThrowsOnBadDefaultValue() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The default value of env parameter "ARRAY_VAR" must be scalar or null, array given.'); $bag = new EnvPlaceholderParameterBag(); $bag->get('env(ARRAY_VAR)'); $bag->set('env(ARRAY_VAR)', []); @@ -151,12 +147,10 @@ class EnvPlaceholderParameterBagTest extends TestCase $this->assertNull($bag->all()['env(NULL_VAR)']); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The default value of an env() parameter must be scalar or null, but "array" given to "env(ARRAY_VAR)". - */ public function testGetThrowsOnBadDefaultValue() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The default value of an env() parameter must be scalar or null, but "array" given to "env(ARRAY_VAR)".'); $bag = new EnvPlaceholderParameterBag(); $bag->set('env(ARRAY_VAR)', []); $bag->get('env(ARRAY_VAR)'); diff --git a/lib/symfony/dependency-injection/Tests/ParameterBag/FrozenParameterBagTest.php b/lib/symfony/dependency-injection/Tests/ParameterBag/FrozenParameterBagTest.php index b168e0c20..ed89c8e4e 100644 --- a/lib/symfony/dependency-injection/Tests/ParameterBag/FrozenParameterBagTest.php +++ b/lib/symfony/dependency-injection/Tests/ParameterBag/FrozenParameterBagTest.php @@ -26,38 +26,30 @@ class FrozenParameterBagTest extends TestCase $this->assertEquals($parameters, $bag->all(), '__construct() takes an array of parameters as its first argument'); } - /** - * @expectedException \LogicException - */ public function testClear() { + $this->expectException('LogicException'); $bag = new FrozenParameterBag([]); $bag->clear(); } - /** - * @expectedException \LogicException - */ public function testSet() { + $this->expectException('LogicException'); $bag = new FrozenParameterBag([]); $bag->set('foo', 'bar'); } - /** - * @expectedException \LogicException - */ public function testAdd() { + $this->expectException('LogicException'); $bag = new FrozenParameterBag([]); $bag->add([]); } - /** - * @expectedException \LogicException - */ public function testRemove() { + $this->expectException('LogicException'); $bag = new FrozenParameterBag(['foo' => 'bar']); $bag->remove('foo'); } diff --git a/lib/symfony/dependency-injection/Tests/ParameterBag/ParameterBagTest.php b/lib/symfony/dependency-injection/Tests/ParameterBag/ParameterBagTest.php index e67e393df..0a75b445b 100644 --- a/lib/symfony/dependency-injection/Tests/ParameterBag/ParameterBagTest.php +++ b/lib/symfony/dependency-injection/Tests/ParameterBag/ParameterBagTest.php @@ -78,12 +78,8 @@ class ParameterBagTest extends TestCase 'fiz' => ['bar' => ['boo' => 12]], ]); - if (method_exists($this, 'expectException')) { - $this->expectException(ParameterNotFoundException::class); - $this->expectExceptionMessage($exceptionMessage); - } else { - $this->setExpectedException(ParameterNotFoundException::class, $exceptionMessage); - } + $this->expectException(ParameterNotFoundException::class); + $this->expectExceptionMessage($exceptionMessage); $bag->get($parameterKey); } diff --git a/lib/symfony/dependency-injection/Tests/ServiceLocatorTest.php b/lib/symfony/dependency-injection/Tests/ServiceLocatorTest.php index aa9ebab68..52466af94 100644 --- a/lib/symfony/dependency-injection/Tests/ServiceLocatorTest.php +++ b/lib/symfony/dependency-injection/Tests/ServiceLocatorTest.php @@ -58,12 +58,10 @@ class ServiceLocatorTest extends TestCase $this->assertSame(2, $i); } - /** - * @expectedException \Psr\Container\NotFoundExceptionInterface - * @expectedExceptionMessage Service "dummy" not found: the container inside "Symfony\Component\DependencyInjection\Tests\ServiceLocatorTest" is a smaller service locator that only knows about the "foo" and "bar" services. - */ public function testGetThrowsOnUndefinedService() { + $this->expectException('Psr\Container\NotFoundExceptionInterface'); + $this->expectExceptionMessage('Service "dummy" not found: the container inside "Symfony\Component\DependencyInjection\Tests\ServiceLocatorTest" is a smaller service locator that only knows about the "foo" and "bar" services.'); $locator = new ServiceLocator([ 'foo' => function () { return 'bar'; }, 'bar' => function () { return 'baz'; }, @@ -72,12 +70,10 @@ class ServiceLocatorTest extends TestCase $locator->get('dummy'); } - /** - * @expectedException \Psr\Container\NotFoundExceptionInterface - * @expectedExceptionMessage The service "foo" has a dependency on a non-existent service "bar". This locator only knows about the "foo" service. - */ public function testThrowsOnUndefinedInternalService() { + $this->expectException('Psr\Container\NotFoundExceptionInterface'); + $this->expectExceptionMessage('The service "foo" has a dependency on a non-existent service "bar". This locator only knows about the "foo" service.'); $locator = new ServiceLocator([ 'foo' => function () use (&$locator) { return $locator->get('bar'); }, ]); @@ -85,12 +81,10 @@ class ServiceLocatorTest extends TestCase $locator->get('foo'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException - * @expectedExceptionMessage Circular reference detected for service "bar", path: "bar -> baz -> bar". - */ public function testThrowsOnCircularReference() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException'); + $this->expectExceptionMessage('Circular reference detected for service "bar", path: "bar -> baz -> bar".'); $locator = new ServiceLocator([ 'foo' => function () use (&$locator) { return $locator->get('bar'); }, 'bar' => function () use (&$locator) { return $locator->get('baz'); }, @@ -100,12 +94,10 @@ class ServiceLocatorTest extends TestCase $locator->get('foo'); } - /** - * @expectedException \Psr\Container\NotFoundExceptionInterface - * @expectedExceptionMessage Service "foo" not found: even though it exists in the app's container, the container inside "caller" is a smaller service locator that only knows about the "bar" service. Unless you need extra laziness, try using dependency injection instead. Otherwise, you need to declare it using "SomeServiceSubscriber::getSubscribedServices()". - */ public function testThrowsInServiceSubscriber() { + $this->expectException('Psr\Container\NotFoundExceptionInterface'); + $this->expectExceptionMessage('Service "foo" not found: even though it exists in the app\'s container, the container inside "caller" is a smaller service locator that only knows about the "bar" service. Unless you need extra laziness, try using dependency injection instead. Otherwise, you need to declare it using "SomeServiceSubscriber::getSubscribedServices()".'); $container = new Container(); $container->set('foo', new \stdClass()); $subscriber = new SomeServiceSubscriber(); @@ -115,12 +107,10 @@ class ServiceLocatorTest extends TestCase $subscriber->getFoo(); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage Service "foo" not found: even though it exists in the app's container, the container inside "foo" is a smaller service locator that is empty... Try using dependency injection instead. - */ public function testGetThrowsServiceNotFoundException() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $this->expectExceptionMessage('Service "foo" not found: even though it exists in the app\'s container, the container inside "foo" is a smaller service locator that is empty... Try using dependency injection instead.'); $container = new Container(); $container->set('foo', new \stdClass()); diff --git a/lib/symfony/dotenv/Dotenv.php b/lib/symfony/dotenv/Dotenv.php index b43529abd..c2475f204 100644 --- a/lib/symfony/dotenv/Dotenv.php +++ b/lib/symfony/dotenv/Dotenv.php @@ -38,8 +38,7 @@ final class Dotenv /** * Loads one or several .env files. * - * @param string $path A file to load - * @param ...string $paths A list of additional files to load + * @param string $path A file to load * * @throws FormatException when a file has a syntax error * @throws PathException when a file does not exist or is not readable @@ -184,29 +183,24 @@ final class Dotenv throw $this->createFormatException('Whitespace are not supported before the value'); } + $loadedVars = array_flip(explode(',', isset($_SERVER['SYMFONY_DOTENV_VARS']) ? $_SERVER['SYMFONY_DOTENV_VARS'] : (isset($_ENV['SYMFONY_DOTENV_VARS']) ? $_ENV['SYMFONY_DOTENV_VARS'] : ''))); + unset($loadedVars['']); $v = ''; do { if ("'" === $this->data[$this->cursor]) { - $value = ''; - ++$this->cursor; + $len = 0; - while ("\n" !== $this->data[$this->cursor]) { - if ("'" === $this->data[$this->cursor]) { - break; - } - $value .= $this->data[$this->cursor]; - ++$this->cursor; + do { + if ($this->cursor + ++$len === $this->end) { + $this->cursor += $len; - if ($this->cursor === $this->end) { throw $this->createFormatException('Missing quote to end the value'); } - } - if ("\n" === $this->data[$this->cursor]) { - throw $this->createFormatException('Missing quote to end the value'); - } - ++$this->cursor; - $v .= $value; + } while ("'" !== $this->data[$this->cursor + $len]); + + $v .= substr($this->data, 1 + $this->cursor, $len - 1); + $this->cursor += 1 + $len; } elseif ('"' === $this->data[$this->cursor]) { $value = ''; ++$this->cursor; @@ -225,8 +219,8 @@ final class Dotenv ++$this->cursor; $value = str_replace(['\\"', '\r', '\n'], ['"', "\r", "\n"], $value); $resolvedValue = $value; - $resolvedValue = $this->resolveVariables($resolvedValue); - $resolvedValue = $this->resolveCommands($resolvedValue); + $resolvedValue = $this->resolveVariables($resolvedValue, $loadedVars); + $resolvedValue = $this->resolveCommands($resolvedValue, $loadedVars); $resolvedValue = str_replace('\\\\', '\\', $resolvedValue); $v .= $resolvedValue; } else { @@ -248,8 +242,8 @@ final class Dotenv } $value = rtrim($value); $resolvedValue = $value; - $resolvedValue = $this->resolveVariables($resolvedValue); - $resolvedValue = $this->resolveCommands($resolvedValue); + $resolvedValue = $this->resolveVariables($resolvedValue, $loadedVars); + $resolvedValue = $this->resolveCommands($resolvedValue, $loadedVars); $resolvedValue = str_replace('\\\\', '\\', $resolvedValue); if ($resolvedValue === $value && preg_match('/\s+/', $value)) { @@ -302,7 +296,7 @@ final class Dotenv } } - private function resolveCommands($value) + private function resolveCommands($value, $loadedVars) { if (false === strpos($value, '$')) { return $value; @@ -318,7 +312,7 @@ final class Dotenv ) /x'; - return preg_replace_callback($regex, function ($matches) { + return preg_replace_callback($regex, function ($matches) use ($loadedVars) { if ('\\' === $matches[1]) { return substr($matches[0], 1); } @@ -333,7 +327,15 @@ final class Dotenv $process = new Process('echo '.$matches[0]); $process->inheritEnvironmentVariables(true); - $process->setEnv($this->values); + + $env = []; + foreach ($this->values as $name => $value) { + if (isset($loadedVars[$name]) || (!isset($_ENV[$name]) && !(isset($_SERVER[$name]) && 0 !== strpos($name, 'HTTP_')))) { + $env[$name] = $value; + } + } + $process->setEnv($env); + try { $process->mustRun(); } catch (ProcessException $e) { @@ -344,7 +346,7 @@ final class Dotenv }, $value); } - private function resolveVariables($value) + private function resolveVariables($value, array $loadedVars) { if (false === strpos($value, '$')) { return $value; @@ -360,7 +362,7 @@ final class Dotenv (?P\})? # optional closing brace /x'; - $value = preg_replace_callback($regex, function ($matches) { + $value = preg_replace_callback($regex, function ($matches) use ($loadedVars) { // odd number of backslashes means the $ character is escaped if (1 === \strlen($matches['backslashes']) % 2) { return substr($matches[0], 1); @@ -376,14 +378,16 @@ final class Dotenv } $name = $matches['name']; - if (isset($this->values[$name])) { + if (isset($loadedVars[$name]) && isset($this->values[$name])) { $value = $this->values[$name]; - } elseif (isset($_SERVER[$name]) && 0 !== strpos($name, 'HTTP_')) { - $value = $_SERVER[$name]; } elseif (isset($_ENV[$name])) { $value = $_ENV[$name]; + } elseif (isset($_SERVER[$name]) && 0 !== strpos($name, 'HTTP_')) { + $value = $_SERVER[$name]; + } elseif (isset($this->values[$name])) { + $value = $this->values[$name]; } else { - $value = (string) getenv($name); + $value = ''; } if (!$matches['opening_brace'] && isset($matches['closing_brace'])) { diff --git a/lib/symfony/dotenv/Tests/DotenvTest.php b/lib/symfony/dotenv/Tests/DotenvTest.php index 97ae5090c..1e493f24b 100644 --- a/lib/symfony/dotenv/Tests/DotenvTest.php +++ b/lib/symfony/dotenv/Tests/DotenvTest.php @@ -40,6 +40,7 @@ class DotenvTest extends TestCase ['FOO', "Missing = in the environment variable declaration in \".env\" at line 1.\n...FOO...\n ^ line 1 offset 3"], ['FOO="foo', "Missing quote to end the value in \".env\" at line 1.\n...FOO=\"foo...\n ^ line 1 offset 8"], ['FOO=\'foo', "Missing quote to end the value in \".env\" at line 1.\n...FOO='foo...\n ^ line 1 offset 8"], + ['FOO=\'foo'."\n", "Missing quote to end the value in \".env\" at line 1.\n...FOO='foo\\n...\n ^ line 1 offset 9"], ['export FOO', "Unable to unset an environment variable in \".env\" at line 1.\n...export FOO...\n ^ line 1 offset 10"], ['FOO=${FOO', "Unclosed braces on variable expansion in \".env\" at line 1.\n...FOO=\${FOO...\n ^ line 1 offset 9"], ]; @@ -63,6 +64,7 @@ class DotenvTest extends TestCase public function getEnvData() { putenv('LOCAL=local'); + $_ENV['LOCAL'] = 'local'; $_ENV['REMOTE'] = 'remote'; $tests = [ @@ -104,6 +106,7 @@ class DotenvTest extends TestCase ['FOO="bar\rfoo"', ['FOO' => "bar\rfoo"]], ['FOO=\'bar\nfoo\'', ['FOO' => 'bar\nfoo']], ['FOO=\'bar\rfoo\'', ['FOO' => 'bar\rfoo']], + ["FOO='bar\nfoo'", ['FOO' => "bar\nfoo"]], ['FOO=" FOO "', ['FOO' => ' FOO ']], ['FOO=" "', ['FOO' => ' ']], ['PATH="c:\\\\"', ['PATH' => 'c:\\']], @@ -200,11 +203,9 @@ class DotenvTest extends TestCase $this->assertSame('BAZ', $bar); } - /** - * @expectedException \Symfony\Component\Dotenv\Exception\PathException - */ public function testLoadDirectory() { + $this->expectException('Symfony\Component\Dotenv\Exception\PathException'); $dotenv = new Dotenv(); $dotenv->load(__DIR__); } @@ -297,4 +298,20 @@ class DotenvTest extends TestCase $this->assertSame('baz1', getenv('BAZ')); $this->assertSame('/var/www', getenv('DOCUMENT_ROOT')); } + + public function testGetVariablesValueFromEnvFirst() + { + $_ENV['APP_ENV'] = 'prod'; + $dotenv = new Dotenv(true); + + $test = "APP_ENV=dev\nTEST1=foo1_\${APP_ENV}"; + $values = $dotenv->parse($test); + $this->assertSame('foo1_prod', $values['TEST1']); + + if ('\\' !== \DIRECTORY_SEPARATOR) { + $test = "APP_ENV=dev\nTEST2=foo2_\$(php -r 'echo \$_SERVER[\"APP_ENV\"];')"; + $values = $dotenv->parse($test); + $this->assertSame('foo2_prod', $values['TEST2']); + } + } } diff --git a/lib/symfony/dotenv/composer.json b/lib/symfony/dotenv/composer.json index 3bcfd89c8..e35339c98 100644 --- a/lib/symfony/dotenv/composer.json +++ b/lib/symfony/dotenv/composer.json @@ -19,7 +19,7 @@ "php": "^5.5.9|>=7.0.8" }, "require-dev": { - "symfony/process": "~3.2|~4.0" + "symfony/process": "^3.4.2|^4.0" }, "autoload": { "psr-4": { "Symfony\\Component\\Dotenv\\": "" }, diff --git a/lib/symfony/event-dispatcher/ContainerAwareEventDispatcher.php b/lib/symfony/event-dispatcher/ContainerAwareEventDispatcher.php index aeafd9ec2..1b33e1cab 100644 --- a/lib/symfony/event-dispatcher/ContainerAwareEventDispatcher.php +++ b/lib/symfony/event-dispatcher/ContainerAwareEventDispatcher.php @@ -11,6 +11,7 @@ namespace Symfony\Component\EventDispatcher; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\DependencyInjection\ContainerInterface; /** @@ -42,7 +43,7 @@ class ContainerAwareEventDispatcher extends EventDispatcher $this->container = $container; $class = \get_class($this); - if ($this instanceof \PHPUnit_Framework_MockObject_MockObject || $this instanceof \Prophecy\Doubler\DoubleInterface) { + if ($this instanceof \PHPUnit_Framework_MockObject_MockObject || $this instanceof MockObject || $this instanceof \Prophecy\Doubler\DoubleInterface) { $class = get_parent_class($class); } if (__CLASS__ !== $class) { diff --git a/lib/symfony/event-dispatcher/EventDispatcher.php b/lib/symfony/event-dispatcher/EventDispatcher.php index 968e345b3..207790f06 100644 --- a/lib/symfony/event-dispatcher/EventDispatcher.php +++ b/lib/symfony/event-dispatcher/EventDispatcher.php @@ -79,7 +79,7 @@ class EventDispatcher implements EventDispatcherInterface public function getListenerPriority($eventName, $listener) { if (empty($this->listeners[$eventName])) { - return; + return null; } if (\is_array($listener) && isset($listener[0]) && $listener[0] instanceof \Closure) { @@ -97,6 +97,8 @@ class EventDispatcher implements EventDispatcherInterface } } } + + return null; } /** diff --git a/lib/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php b/lib/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php index b157659dc..359e6005f 100644 --- a/lib/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php +++ b/lib/symfony/event-dispatcher/Tests/AbstractEventDispatcherTest.php @@ -267,7 +267,7 @@ abstract class AbstractEventDispatcherTest extends TestCase } /** - * @see https://bugs.php.net/bug.php?id=62976 + * @see https://bugs.php.net/62976 * * This bug affects: * - The PHP 5.3 branch for versions < 5.3.18 diff --git a/lib/symfony/event-dispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php b/lib/symfony/event-dispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php index 801471b47..61c047af3 100644 --- a/lib/symfony/event-dispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php +++ b/lib/symfony/event-dispatcher/Tests/DependencyInjection/RegisterListenersPassTest.php @@ -22,11 +22,10 @@ class RegisterListenersPassTest extends TestCase /** * Tests that event subscribers not implementing EventSubscriberInterface * trigger an exception. - * - * @expectedException \InvalidArgumentException */ public function testEventSubscriberWithoutInterface() { + $this->expectException('InvalidArgumentException'); $builder = new ContainerBuilder(); $builder->register('event_dispatcher'); $builder->register('my_event_subscriber', 'stdClass') @@ -38,10 +37,6 @@ class RegisterListenersPassTest extends TestCase public function testValidEventSubscriber() { - $services = [ - 'my_event_subscriber' => [0 => []], - ]; - $builder = new ContainerBuilder(); $eventDispatcherDefinition = $builder->register('event_dispatcher'); $builder->register('my_event_subscriber', 'Symfony\Component\EventDispatcher\Tests\DependencyInjection\SubscriberService') @@ -63,12 +58,10 @@ class RegisterListenersPassTest extends TestCase $this->assertEquals($expectedCalls, $eventDispatcherDefinition->getMethodCalls()); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The service "foo" tagged "kernel.event_listener" must not be abstract. - */ public function testAbstractEventListener() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The service "foo" tagged "kernel.event_listener" must not be abstract.'); $container = new ContainerBuilder(); $container->register('foo', 'stdClass')->setAbstract(true)->addTag('kernel.event_listener', []); $container->register('event_dispatcher', 'stdClass'); @@ -77,12 +70,10 @@ class RegisterListenersPassTest extends TestCase $registerListenersPass->process($container); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The service "foo" tagged "kernel.event_subscriber" must not be abstract. - */ public function testAbstractEventSubscriber() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The service "foo" tagged "kernel.event_subscriber" must not be abstract.'); $container = new ContainerBuilder(); $container->register('foo', 'stdClass')->setAbstract(true)->addTag('kernel.event_subscriber', []); $container->register('event_dispatcher', 'stdClass'); @@ -128,12 +119,10 @@ class RegisterListenersPassTest extends TestCase $this->assertTrue($container->getDefinition('foo')->hasTag('container.hot_path')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage You have requested a non-existent parameter "subscriber.class" - */ public function testEventSubscriberUnresolvableClassName() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('You have requested a non-existent parameter "subscriber.class"'); $container = new ContainerBuilder(); $container->register('foo', '%subscriber.class%')->addTag('kernel.event_subscriber', []); $container->register('event_dispatcher', 'stdClass'); diff --git a/lib/symfony/event-dispatcher/Tests/GenericEventTest.php b/lib/symfony/event-dispatcher/Tests/GenericEventTest.php index 461f86161..f0f0d71f2 100644 --- a/lib/symfony/event-dispatcher/Tests/GenericEventTest.php +++ b/lib/symfony/event-dispatcher/Tests/GenericEventTest.php @@ -61,14 +61,14 @@ class GenericEventTest extends TestCase public function testSetArguments() { $result = $this->event->setArguments(['foo' => 'bar']); - $this->assertAttributeSame(['foo' => 'bar'], 'arguments', $this->event); + $this->assertSame(['foo' => 'bar'], $this->event->getArguments()); $this->assertSame($this->event, $result); } public function testSetArgument() { $result = $this->event->setArgument('foo2', 'bar2'); - $this->assertAttributeSame(['name' => 'Event', 'foo2' => 'bar2'], 'arguments', $this->event); + $this->assertSame(['name' => 'Event', 'foo2' => 'bar2'], $this->event->getArguments()); $this->assertEquals($this->event, $result); } @@ -78,11 +78,9 @@ class GenericEventTest extends TestCase $this->assertEquals('Event', $this->event->getArgument('name')); } - /** - * @expectedException \InvalidArgumentException - */ public function testGetArgException() { + $this->expectException('\InvalidArgumentException'); $this->event->getArgument('nameNotExist'); } @@ -92,20 +90,20 @@ class GenericEventTest extends TestCase $this->assertEquals('Event', $this->event['name']); // test getting invalid arg - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('InvalidArgumentException'); + $this->expectException('InvalidArgumentException'); $this->assertFalse($this->event['nameNotExist']); } public function testOffsetSet() { $this->event['foo2'] = 'bar2'; - $this->assertAttributeSame(['name' => 'Event', 'foo2' => 'bar2'], 'arguments', $this->event); + $this->assertSame(['name' => 'Event', 'foo2' => 'bar2'], $this->event->getArguments()); } public function testOffsetUnset() { unset($this->event['name']); - $this->assertAttributeSame([], 'arguments', $this->event); + $this->assertSame([], $this->event->getArguments()); } public function testOffsetIsset() diff --git a/lib/symfony/event-dispatcher/Tests/ImmutableEventDispatcherTest.php b/lib/symfony/event-dispatcher/Tests/ImmutableEventDispatcherTest.php index c52fefe50..da8502ab9 100644 --- a/lib/symfony/event-dispatcher/Tests/ImmutableEventDispatcherTest.php +++ b/lib/symfony/event-dispatcher/Tests/ImmutableEventDispatcherTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\EventDispatcher\Tests; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\ImmutableEventDispatcher; @@ -21,7 +22,7 @@ use Symfony\Component\EventDispatcher\ImmutableEventDispatcher; class ImmutableEventDispatcherTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $innerDispatcher; @@ -39,13 +40,14 @@ class ImmutableEventDispatcherTest extends TestCase public function testDispatchDelegates() { $event = new Event(); + $resultEvent = new Event(); $this->innerDispatcher->expects($this->once()) ->method('dispatch') ->with('event', $event) - ->willReturn('result'); + ->willReturn($resultEvent); - $this->assertSame('result', $this->dispatcher->dispatch('event', $event)); + $this->assertSame($resultEvent, $this->dispatcher->dispatch('event', $event)); } public function testGetListenersDelegates() @@ -53,9 +55,9 @@ class ImmutableEventDispatcherTest extends TestCase $this->innerDispatcher->expects($this->once()) ->method('getListeners') ->with('event') - ->willReturn('result'); + ->willReturn(['result']); - $this->assertSame('result', $this->dispatcher->getListeners('event')); + $this->assertSame(['result'], $this->dispatcher->getListeners('event')); } public function testHasListenersDelegates() @@ -63,42 +65,34 @@ class ImmutableEventDispatcherTest extends TestCase $this->innerDispatcher->expects($this->once()) ->method('hasListeners') ->with('event') - ->willReturn('result'); + ->willReturn(true); - $this->assertSame('result', $this->dispatcher->hasListeners('event')); + $this->assertTrue($this->dispatcher->hasListeners('event')); } - /** - * @expectedException \BadMethodCallException - */ public function testAddListenerDisallowed() { + $this->expectException('\BadMethodCallException'); $this->dispatcher->addListener('event', function () { return 'foo'; }); } - /** - * @expectedException \BadMethodCallException - */ public function testAddSubscriberDisallowed() { + $this->expectException('\BadMethodCallException'); $subscriber = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventSubscriberInterface')->getMock(); $this->dispatcher->addSubscriber($subscriber); } - /** - * @expectedException \BadMethodCallException - */ public function testRemoveListenerDisallowed() { + $this->expectException('\BadMethodCallException'); $this->dispatcher->removeListener('event', function () { return 'foo'; }); } - /** - * @expectedException \BadMethodCallException - */ public function testRemoveSubscriberDisallowed() { + $this->expectException('\BadMethodCallException'); $subscriber = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventSubscriberInterface')->getMock(); $this->dispatcher->removeSubscriber($subscriber); diff --git a/lib/symfony/filesystem/Filesystem.php b/lib/symfony/filesystem/Filesystem.php index a6e372ebf..cd456c784 100644 --- a/lib/symfony/filesystem/Filesystem.php +++ b/lib/symfony/filesystem/Filesystem.php @@ -52,7 +52,7 @@ class Filesystem } if ($doCopy) { - // https://bugs.php.net/bug.php?id=64634 + // https://bugs.php.net/64634 if (false === $source = @fopen($originFile, 'r')) { throw new IOException(sprintf('Failed to copy "%s" to "%s" because source file could not be opened for reading.', $originFile, $targetFile), 0, null, $originFile); } @@ -280,7 +280,7 @@ class Filesystem 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 + // See https://bugs.php.net/54097 & https://php.net/rename#113943 $this->mirror($origin, $target, null, ['override' => $overwrite, 'delete' => $overwrite]); $this->remove($origin); @@ -413,12 +413,12 @@ class Filesystem public function readlink($path, $canonicalize = false) { if (!$canonicalize && !is_link($path)) { - return; + return null; } if ($canonicalize) { if (!$this->exists($path)) { - return; + return null; } if ('\\' === \DIRECTORY_SEPARATOR) { @@ -743,6 +743,11 @@ class Filesystem return 2 === \count($components) ? [$components[0], $components[1]] : [null, $components[0]]; } + /** + * @param callable $func + * + * @return mixed + */ private static function box($func) { self::$lastError = null; diff --git a/lib/symfony/filesystem/Tests/FilesystemTest.php b/lib/symfony/filesystem/Tests/FilesystemTest.php index 186b2ef36..a5b7f6dce 100644 --- a/lib/symfony/filesystem/Tests/FilesystemTest.php +++ b/lib/symfony/filesystem/Tests/FilesystemTest.php @@ -29,22 +29,18 @@ class FilesystemTest extends FilesystemTestCase $this->assertStringEqualsFile($targetFilePath, 'SOURCE FILE'); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testCopyFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $sourceFilePath = $this->workspace.\DIRECTORY_SEPARATOR.'copy_source_file'; $targetFilePath = $this->workspace.\DIRECTORY_SEPARATOR.'copy_target_file'; $this->filesystem->copy($sourceFilePath, $targetFilePath); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testCopyUnreadableFileFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); // skip test on Windows; PHP can't easily set file as unreadable on Windows if ('\\' === \DIRECTORY_SEPARATOR) { $this->markTestSkipped('This test cannot run on Windows.'); @@ -118,11 +114,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertStringEqualsFile($targetFilePath, 'SOURCE FILE'); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testCopyWithOverrideWithReadOnlyTargetFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); // skip test on Windows; PHP can't easily set file as unwritable on Windows if ('\\' === \DIRECTORY_SEPARATOR) { $this->markTestSkipped('This test cannot run on Windows.'); @@ -159,7 +153,7 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->copy($sourceFilePath, $targetFilePath); - $this->assertTrue(is_dir($targetFileDirectory)); + $this->assertDirectoryExists($targetFileDirectory); $this->assertFileExists($targetFilePath); $this->assertStringEqualsFile($targetFilePath, 'SOURCE FILE'); } @@ -191,7 +185,7 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->mkdir($directory); - $this->assertTrue(is_dir($directory)); + $this->assertDirectoryExists($directory); } public function testMkdirCreatesDirectoriesFromArray() @@ -203,9 +197,9 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->mkdir($directories); - $this->assertTrue(is_dir($basePath.'1')); - $this->assertTrue(is_dir($basePath.'2')); - $this->assertTrue(is_dir($basePath.'3')); + $this->assertDirectoryExists($basePath.'1'); + $this->assertDirectoryExists($basePath.'2'); + $this->assertDirectoryExists($basePath.'3'); } public function testMkdirCreatesDirectoriesFromTraversableObject() @@ -217,16 +211,14 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->mkdir($directories); - $this->assertTrue(is_dir($basePath.'1')); - $this->assertTrue(is_dir($basePath.'2')); - $this->assertTrue(is_dir($basePath.'3')); + $this->assertDirectoryExists($basePath.'1'); + $this->assertDirectoryExists($basePath.'2'); + $this->assertDirectoryExists($basePath.'3'); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testMkdirCreatesDirectoriesFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $basePath = $this->workspace.\DIRECTORY_SEPARATOR; $dir = $basePath.'2'; @@ -244,11 +236,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertFileExists($file); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testTouchFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $file = $this->workspace.\DIRECTORY_SEPARATOR.'1'.\DIRECTORY_SEPARATOR.'2'; $this->filesystem->touch($file); @@ -357,7 +347,7 @@ class FilesystemTest extends FilesystemTestCase // create symlink to dir using trailing forward slash $this->filesystem->symlink($basePath.'dir/', $basePath.'dir-link'); - $this->assertTrue(is_dir($basePath.'dir-link')); + $this->assertDirectoryExists($basePath.'dir-link'); // create symlink to nonexistent dir rmdir($basePath.'dir'); @@ -380,11 +370,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertTrue($this->filesystem->exists($basePath.'folder')); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testFilesExistsFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); if ('\\' !== \DIRECTORY_SEPARATOR) { $this->markTestSkipped('Long file names are an issue on Windows'); } @@ -613,11 +601,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertSame($owner, $this->getFileOwner($link)); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testChownSymlinkFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $this->markAsSkippedIfSymlinkIsMissing(); $file = $this->workspace.\DIRECTORY_SEPARATOR.'file'; @@ -630,11 +616,9 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->chown($link, 'user'.time().mt_rand(1000, 9999)); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testChownLinkFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $this->markAsSkippedIfLinkIsMissing(); $file = $this->workspace.\DIRECTORY_SEPARATOR.'file'; @@ -647,11 +631,9 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->chown($link, 'user'.time().mt_rand(1000, 9999)); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testChownFail() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $this->markAsSkippedIfPosixIsMissing(); $dir = $this->workspace.\DIRECTORY_SEPARATOR.'dir'; @@ -722,11 +704,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertSame($group, $this->getFileGroup($link)); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testChgrpSymlinkFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $this->markAsSkippedIfSymlinkIsMissing(); $file = $this->workspace.\DIRECTORY_SEPARATOR.'file'; @@ -739,11 +719,9 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->chgrp($link, 'user'.time().mt_rand(1000, 9999)); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testChgrpLinkFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $this->markAsSkippedIfLinkIsMissing(); $file = $this->workspace.\DIRECTORY_SEPARATOR.'file'; @@ -756,11 +734,9 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->chgrp($link, 'user'.time().mt_rand(1000, 9999)); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testChgrpFail() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $this->markAsSkippedIfPosixIsMissing(); $dir = $this->workspace.\DIRECTORY_SEPARATOR.'dir'; @@ -781,11 +757,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertFileExists($newPath); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testRenameThrowsExceptionIfTargetAlreadyExists() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $file = $this->workspace.\DIRECTORY_SEPARATOR.'file'; $newPath = $this->workspace.\DIRECTORY_SEPARATOR.'new_file'; @@ -809,11 +783,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertFileExists($newPath); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testRenameThrowsExceptionOnError() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $file = $this->workspace.\DIRECTORY_SEPARATOR.uniqid('fs_test_', true); $newPath = $this->workspace.\DIRECTORY_SEPARATOR.'new_file'; @@ -853,7 +825,7 @@ class FilesystemTest extends FilesystemTestCase $this->assertFalse(is_link($link)); $this->assertFalse(is_file($link)); - $this->assertFalse(is_dir($link)); + $this->assertDirectoryNotExists($link); } public function testSymlinkIsOverwrittenIfPointsToDifferentTarget() @@ -1198,8 +1170,8 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->mirror($sourcePath, $targetPath); - $this->assertTrue(is_dir($targetPath)); - $this->assertTrue(is_dir($targetPath.'directory')); + $this->assertDirectoryExists($targetPath); + $this->assertDirectoryExists($targetPath.'directory'); $this->assertFileEquals($file1, $targetPath.'directory'.\DIRECTORY_SEPARATOR.'file1'); $this->assertFileEquals($file2, $targetPath.'file2'); @@ -1232,7 +1204,7 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->mirror($sourcePath, $targetPath); - $this->assertTrue(is_dir($targetPath)); + $this->assertDirectoryExists($targetPath); $this->filesystem->remove($sourcePath); } @@ -1251,7 +1223,7 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->mirror($sourcePath, $targetPath); - $this->assertTrue(is_dir($targetPath)); + $this->assertDirectoryExists($targetPath); $this->assertFileEquals($sourcePath.'file1', $targetPath.'link1'); $this->assertTrue(is_link($targetPath.\DIRECTORY_SEPARATOR.'link1')); } @@ -1271,7 +1243,7 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->mirror($sourcePath, $targetPath); - $this->assertTrue(is_dir($targetPath)); + $this->assertDirectoryExists($targetPath); $this->assertFileEquals($sourcePath.'/nested/file1.txt', $targetPath.'link1/file1.txt'); $this->assertTrue(is_link($targetPath.\DIRECTORY_SEPARATOR.'link1')); } @@ -1295,7 +1267,7 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->mirror($sourcePath, $targetPath); - $this->assertTrue(is_dir($targetPath)); + $this->assertDirectoryExists($targetPath); $this->assertFileEquals($sourcePath.'/nested/file1.txt', $targetPath.'link1/file1.txt'); $this->assertTrue(is_link($targetPath.\DIRECTORY_SEPARATOR.'link1')); $this->assertEquals('\\' === \DIRECTORY_SEPARATOR ? realpath($sourcePath.'\nested') : 'nested', readlink($targetPath.\DIRECTORY_SEPARATOR.'link1')); @@ -1318,7 +1290,7 @@ class FilesystemTest extends FilesystemTestCase chdir($oldPath); - $this->assertTrue(is_dir($targetPath)); + $this->assertDirectoryExists($targetPath); $this->assertFileExists($targetPath.'source'); $this->assertFileExists($targetPath.'target'); } @@ -1343,7 +1315,7 @@ class FilesystemTest extends FilesystemTestCase chdir($oldPath); - $this->assertTrue(is_dir($targetPath)); + $this->assertDirectoryExists($targetPath); $this->assertFileExists($targetPath.'source'); $this->assertFileNotExists($targetPath.'target'); } @@ -1420,11 +1392,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertFileExists($filename); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testTempnamWithZlibSchemeFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $scheme = 'compress.zlib://'; $dirname = $scheme.$this->workspace; @@ -1445,11 +1415,9 @@ class FilesystemTest extends FilesystemTestCase $this->assertFileNotExists($filename); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testTempnamWithPharSchemeFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); // Skip test if Phar disabled phar.readonly must be 0 in php.ini if (!\Phar::canWrite()) { $this->markTestSkipped('This test cannot run when phar.readonly is 1.'); @@ -1464,11 +1432,9 @@ class FilesystemTest extends FilesystemTestCase $this->filesystem->tempnam($dirname, $pharname.'/bar'); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - */ public function testTempnamWithHTTPSchemeFails() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); $scheme = 'http://'; $dirname = $scheme.$this->workspace; diff --git a/lib/symfony/filesystem/Tests/FilesystemTestCase.php b/lib/symfony/filesystem/Tests/FilesystemTestCase.php index eb6b35ddf..6fb9eba73 100644 --- a/lib/symfony/filesystem/Tests/FilesystemTestCase.php +++ b/lib/symfony/filesystem/Tests/FilesystemTestCase.php @@ -21,7 +21,7 @@ class FilesystemTestCase extends TestCase protected $longPathNamesWindows = []; /** - * @var \Symfony\Component\Filesystem\Filesystem + * @var Filesystem */ protected $filesystem = null; @@ -110,9 +110,8 @@ class FilesystemTestCase extends TestCase $this->markAsSkippedIfPosixIsMissing(); $infos = stat($filepath); - if ($datas = posix_getpwuid($infos['uid'])) { - return $datas['name']; - } + + return ($datas = posix_getpwuid($infos['uid'])) ? $datas['name'] : null; } protected function getFileGroup($filepath) @@ -144,7 +143,7 @@ class FilesystemTestCase extends TestCase $this->markTestSkipped('symlink requires "Create symbolic links" privilege on Windows'); } - // https://bugs.php.net/bug.php?id=69473 + // https://bugs.php.net/69473 if ($relative && '\\' === \DIRECTORY_SEPARATOR && 1 === PHP_ZTS) { $this->markTestSkipped('symlink does not support relative paths on thread safe Windows PHP versions'); } diff --git a/lib/symfony/filesystem/Tests/LockHandlerTest.php b/lib/symfony/filesystem/Tests/LockHandlerTest.php index 14eabc021..d130803d4 100644 --- a/lib/symfony/filesystem/Tests/LockHandlerTest.php +++ b/lib/symfony/filesystem/Tests/LockHandlerTest.php @@ -21,24 +21,20 @@ use Symfony\Component\Filesystem\LockHandler; */ class LockHandlerTest extends TestCase { - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - * @expectedExceptionMessage Failed to create "/a/b/c/d/e": mkdir(): Permission denied. - */ public function testConstructWhenRepositoryDoesNotExist() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); + $this->expectExceptionMessage('Failed to create "/a/b/c/d/e": mkdir(): Permission denied.'); if (!getenv('USER') || 'root' === getenv('USER')) { $this->markTestSkipped('This test will fail if run under superuser'); } new LockHandler('lock', '/a/b/c/d/e'); } - /** - * @expectedException \Symfony\Component\Filesystem\Exception\IOException - * @expectedExceptionMessage The directory "/" is not writable. - */ public function testConstructWhenRepositoryIsNotWriteable() { + $this->expectException('Symfony\Component\Filesystem\Exception\IOException'); + $this->expectExceptionMessage('The directory "/" is not writable.'); if (!getenv('USER') || 'root' === getenv('USER')) { $this->markTestSkipped('This test will fail if run under superuser'); } diff --git a/lib/symfony/finder/Finder.php b/lib/symfony/finder/Finder.php index e933f0784..6624e8407 100644 --- a/lib/symfony/finder/Finder.php +++ b/lib/symfony/finder/Finder.php @@ -541,7 +541,8 @@ class Finder implements \IteratorAggregate, \Countable foreach ((array) $dirs as $dir) { if (is_dir($dir)) { $resolvedDirs[] = $this->normalizeDir($dir); - } elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR)) { + } elseif ($glob = glob($dir, (\defined('GLOB_BRACE') ? GLOB_BRACE : 0) | GLOB_ONLYDIR | GLOB_NOSORT)) { + sort($glob); $resolvedDirs = array_merge($resolvedDirs, array_map([$this, 'normalizeDir'], $glob)); } else { throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir)); diff --git a/lib/symfony/finder/Iterator/SortableIterator.php b/lib/symfony/finder/Iterator/SortableIterator.php index 3c7157adb..e67997d11 100644 --- a/lib/symfony/finder/Iterator/SortableIterator.php +++ b/lib/symfony/finder/Iterator/SortableIterator.php @@ -38,11 +38,11 @@ class SortableIterator implements \IteratorAggregate $this->iterator = $iterator; if (self::SORT_BY_NAME === $sort) { - $this->sort = function ($a, $b) { + $this->sort = static function ($a, $b) { return strcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname()); }; } elseif (self::SORT_BY_TYPE === $sort) { - $this->sort = function ($a, $b) { + $this->sort = static function ($a, $b) { if ($a->isDir() && $b->isFile()) { return -1; } elseif ($a->isFile() && $b->isDir()) { @@ -52,15 +52,15 @@ class SortableIterator implements \IteratorAggregate return strcmp($a->getRealPath() ?: $a->getPathname(), $b->getRealPath() ?: $b->getPathname()); }; } elseif (self::SORT_BY_ACCESSED_TIME === $sort) { - $this->sort = function ($a, $b) { + $this->sort = static function ($a, $b) { return $a->getATime() - $b->getATime(); }; } elseif (self::SORT_BY_CHANGED_TIME === $sort) { - $this->sort = function ($a, $b) { + $this->sort = static function ($a, $b) { return $a->getCTime() - $b->getCTime(); }; } elseif (self::SORT_BY_MODIFIED_TIME === $sort) { - $this->sort = function ($a, $b) { + $this->sort = static function ($a, $b) { return $a->getMTime() - $b->getMTime(); }; } elseif (\is_callable($sort)) { diff --git a/lib/symfony/finder/Tests/FinderTest.php b/lib/symfony/finder/Tests/FinderTest.php index c0eac6da1..442186d2b 100644 --- a/lib/symfony/finder/Tests/FinderTest.php +++ b/lib/symfony/finder/Tests/FinderTest.php @@ -311,11 +311,9 @@ class FinderTest extends Iterator\RealIteratorTestCase $this->assertIterator($expected, $iterator); } - /** - * @expectedException \InvalidArgumentException - */ public function testInWithNonExistentDirectory() { + $this->expectException('InvalidArgumentException'); $finder = new Finder(); $finder->in('foobar'); } @@ -328,11 +326,9 @@ class FinderTest extends Iterator\RealIteratorTestCase $this->assertIterator($this->toAbsoluteFixtures(['A/B/C/abc.dat', 'copy/A/B/C/abc.dat.copy']), $finder); } - /** - * @expectedException \InvalidArgumentException - */ public function testInWithNonDirectoryGlob() { + $this->expectException('InvalidArgumentException'); $finder = new Finder(); $finder->in(__DIR__.'/Fixtures/A/a*'); } @@ -349,11 +345,9 @@ class FinderTest extends Iterator\RealIteratorTestCase $this->assertIterator($this->toAbsoluteFixtures(['A/B/C/abc.dat', 'copy/A/B/C/abc.dat.copy']), $finder); } - /** - * @expectedException \LogicException - */ public function testGetIteratorWithoutIn() { + $this->expectException('LogicException'); $finder = Finder::create(); $finder->getIterator(); } @@ -481,11 +475,9 @@ class FinderTest extends Iterator\RealIteratorTestCase $this->assertCount($i, $files); } - /** - * @expectedException \LogicException - */ public function testCountWithoutIn() { + $this->expectException('LogicException'); $finder = Finder::create()->files(); \count($finder); } @@ -710,12 +702,8 @@ class FinderTest extends Iterator\RealIteratorTestCase $this->fail('Finder should throw an exception when opening a non-readable directory.'); } catch (\Exception $e) { $expectedExceptionClass = 'Symfony\\Component\\Finder\\Exception\\AccessDeniedException'; - if ($e instanceof \PHPUnit_Framework_ExpectationFailedException) { - $this->fail(sprintf("Expected exception:\n%s\nGot:\n%s\nWith comparison failure:\n%s", $expectedExceptionClass, 'PHPUnit_Framework_ExpectationFailedException', $e->getComparisonFailure()->getExpectedAsString())); - } - if ($e instanceof \PHPUnit\Framework\ExpectationFailedException) { - $this->fail(sprintf("Expected exception:\n%s\nGot:\n%s\nWith comparison failure:\n%s", $expectedExceptionClass, '\PHPUnit\Framework\ExpectationFailedException', $e->getComparisonFailure()->getExpectedAsString())); + $this->fail(sprintf("Expected exception:\n%s\nGot:\n%s\nWith comparison failure:\n%s", $expectedExceptionClass, 'PHPUnit\Framework\ExpectationFailedException', $e->getComparisonFailure()->getExpectedAsString())); } $this->assertInstanceOf($expectedExceptionClass, $e); diff --git a/lib/symfony/finder/Tests/Iterator/CustomFilterIteratorTest.php b/lib/symfony/finder/Tests/Iterator/CustomFilterIteratorTest.php index ad0187e03..56d958cb6 100644 --- a/lib/symfony/finder/Tests/Iterator/CustomFilterIteratorTest.php +++ b/lib/symfony/finder/Tests/Iterator/CustomFilterIteratorTest.php @@ -15,11 +15,9 @@ use Symfony\Component\Finder\Iterator\CustomFilterIterator; class CustomFilterIteratorTest extends IteratorTestCase { - /** - * @expectedException \InvalidArgumentException - */ public function testWithInvalidFilter() { + $this->expectException('InvalidArgumentException'); new CustomFilterIterator(new Iterator(), ['foo']); } diff --git a/lib/symfony/finder/Tests/Iterator/IteratorTestCase.php b/lib/symfony/finder/Tests/Iterator/IteratorTestCase.php index 796dc6ac3..c7dfd79e3 100644 --- a/lib/symfony/finder/Tests/Iterator/IteratorTestCase.php +++ b/lib/symfony/finder/Tests/Iterator/IteratorTestCase.php @@ -44,9 +44,8 @@ abstract class IteratorTestCase extends TestCase * $a and $b such that $a goes before $b in $expected, the method * asserts that any element of $a goes before any element of $b * in the sequence generated by $iterator - * @param \Traversable $iterator */ - protected function assertOrderedIteratorForGroups($expected, \Traversable $iterator) + protected function assertOrderedIteratorForGroups(array $expected, \Traversable $iterator) { $values = array_values(array_map(function (\SplFileInfo $fileinfo) { return $fileinfo->getPathname(); }, iterator_to_array($iterator))); @@ -63,11 +62,8 @@ abstract class IteratorTestCase extends TestCase /** * Same as IteratorTestCase::assertIterator with foreach usage. - * - * @param array $expected - * @param \Traversable $iterator */ - protected function assertIteratorInForeach($expected, \Traversable $iterator) + protected function assertIteratorInForeach(array $expected, \Traversable $iterator) { $values = []; foreach ($iterator as $file) { @@ -83,11 +79,8 @@ abstract class IteratorTestCase extends TestCase /** * Same as IteratorTestCase::assertOrderedIterator with foreach usage. - * - * @param array $expected - * @param \Traversable $iterator */ - protected function assertOrderedIteratorInForeach($expected, \Traversable $iterator) + protected function assertOrderedIteratorInForeach(array $expected, \Traversable $iterator) { $values = []; foreach ($iterator as $file) { diff --git a/lib/symfony/finder/Tests/Iterator/SortableIteratorTest.php b/lib/symfony/finder/Tests/Iterator/SortableIteratorTest.php index 57f1e096a..118c4769f 100644 --- a/lib/symfony/finder/Tests/Iterator/SortableIteratorTest.php +++ b/lib/symfony/finder/Tests/Iterator/SortableIteratorTest.php @@ -33,11 +33,7 @@ class SortableIteratorTest extends RealIteratorTestCase if (!\is_callable($mode)) { switch ($mode) { case SortableIterator::SORT_BY_ACCESSED_TIME: - if ('\\' === \DIRECTORY_SEPARATOR) { - touch(self::toAbsolute('.git')); - } else { - file_get_contents(self::toAbsolute('.git')); - } + touch(self::toAbsolute('.git')); sleep(1); file_get_contents(self::toAbsolute('.bar')); break; diff --git a/lib/symfony/framework-bundle/CHANGELOG.md b/lib/symfony/framework-bundle/CHANGELOG.md index fcbe4ffa7..f04942dbc 100644 --- a/lib/symfony/framework-bundle/CHANGELOG.md +++ b/lib/symfony/framework-bundle/CHANGELOG.md @@ -19,17 +19,17 @@ CHANGELOG * Deprecated the `KernelTestCase::getPhpUnitXmlDir()` and `KernelTestCase::getPhpUnitCliConfigArgument()` methods. * Deprecated `AddCacheClearerPass`, use tagged iterator arguments instead. * Deprecated `AddCacheWarmerPass`, use tagged iterator arguments instead. - * Deprecated `TranslationDumperPass`, use + * Deprecated `TranslationDumperPass`, use `Symfony\Component\Translation\DependencyInjection\TranslationDumperPass` instead - * Deprecated `TranslationExtractorPass`, use + * Deprecated `TranslationExtractorPass`, use `Symfony\Component\Translation\DependencyInjection\TranslationExtractorPass` instead - * Deprecated `TranslatorPass`, use + * Deprecated `TranslatorPass`, use `Symfony\Component\Translation\DependencyInjection\TranslatorPass` instead * Added `command` attribute to the `console.command` tag which takes the command name as value, using it makes the command lazy * Added `cache:pool:prune` command to allow manual stale cache item pruning of supported PSR-6 and PSR-16 cache pool implementations - * Deprecated `Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader`, use + * Deprecated `Symfony\Bundle\FrameworkBundle\Translation\TranslationLoader`, use `Symfony\Component\Translation\Reader\TranslationReader` instead * Deprecated `translation.loader` service, use `translation.reader` instead * `AssetsInstallCommand::__construct()` now takes an instance of diff --git a/lib/symfony/framework-bundle/CacheWarmer/AbstractPhpFileCacheWarmer.php b/lib/symfony/framework-bundle/CacheWarmer/AbstractPhpFileCacheWarmer.php index 43cbb7968..9e0984dfb 100644 --- a/lib/symfony/framework-bundle/CacheWarmer/AbstractPhpFileCacheWarmer.php +++ b/lib/symfony/framework-bundle/CacheWarmer/AbstractPhpFileCacheWarmer.php @@ -16,6 +16,7 @@ use Symfony\Component\Cache\Adapter\AdapterInterface; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\Adapter\PhpArrayAdapter; use Symfony\Component\Cache\Adapter\ProxyAdapter; +use Symfony\Component\Config\Resource\ClassExistenceResource; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; /** @@ -54,13 +55,13 @@ abstract class AbstractPhpFileCacheWarmer implements CacheWarmerInterface { $arrayAdapter = new ArrayAdapter(); - spl_autoload_register([PhpArrayAdapter::class, 'throwOnRequiredClass']); + spl_autoload_register([ClassExistenceResource::class, 'throwOnRequiredClass']); try { if (!$this->doWarmUp($cacheDir, $arrayAdapter)) { return; } } finally { - spl_autoload_unregister([PhpArrayAdapter::class, 'throwOnRequiredClass']); + spl_autoload_unregister([ClassExistenceResource::class, 'throwOnRequiredClass']); } // the ArrayAdapter stores the values serialized @@ -83,8 +84,18 @@ abstract class AbstractPhpFileCacheWarmer implements CacheWarmerInterface } /** - * @param string $cacheDir - * @param ArrayAdapter $arrayAdapter + * @internal + */ + final protected function ignoreAutoloadException($class, \Exception $exception) + { + try { + ClassExistenceResource::throwOnRequiredClass($class, $exception); + } catch (\ReflectionException $e) { + } + } + + /** + * @param string $cacheDir * * @return bool false if there is nothing to warm-up */ diff --git a/lib/symfony/framework-bundle/CacheWarmer/AnnotationsCacheWarmer.php b/lib/symfony/framework-bundle/CacheWarmer/AnnotationsCacheWarmer.php index 3c32cb1c4..3859e07f4 100644 --- a/lib/symfony/framework-bundle/CacheWarmer/AnnotationsCacheWarmer.php +++ b/lib/symfony/framework-bundle/CacheWarmer/AnnotationsCacheWarmer.php @@ -31,10 +31,9 @@ class AnnotationsCacheWarmer extends AbstractPhpFileCacheWarmer private $debug; /** - * @param Reader $annotationReader - * @param string $phpArrayFile The PHP file where annotations are cached - * @param CacheItemPoolInterface $fallbackPool The pool where runtime-discovered annotations are cached - * @param bool $debug Run in debug mode + * @param string $phpArrayFile The PHP file where annotations are cached + * @param CacheItemPoolInterface $fallbackPool The pool where runtime-discovered annotations are cached + * @param bool $debug Run in debug mode */ public function __construct(Reader $annotationReader, $phpArrayFile, CacheItemPoolInterface $fallbackPool, $excludeRegexp = null, $debug = false) { @@ -64,17 +63,8 @@ class AnnotationsCacheWarmer extends AbstractPhpFileCacheWarmer } try { $this->readAllComponents($reader, $class); - } catch (\ReflectionException $e) { - // ignore failing reflection - } catch (AnnotationException $e) { - /* - * Ignore any AnnotationException to not break the cache warming process if an Annotation is badly - * configured or could not be found / read / etc. - * - * In particular cases, an Annotation in your code can be used and defined only for a specific - * environment but is always added to the annotations.map file by some Symfony default behaviors, - * and you always end up with a not found Annotation. - */ + } catch (\Exception $e) { + $this->ignoreAutoloadException($class, $e); } } @@ -84,14 +74,32 @@ class AnnotationsCacheWarmer extends AbstractPhpFileCacheWarmer private function readAllComponents(Reader $reader, $class) { $reflectionClass = new \ReflectionClass($class); - $reader->getClassAnnotations($reflectionClass); + + try { + $reader->getClassAnnotations($reflectionClass); + } catch (AnnotationException $e) { + /* + * Ignore any AnnotationException to not break the cache warming process if an Annotation is badly + * configured or could not be found / read / etc. + * + * In particular cases, an Annotation in your code can be used and defined only for a specific + * environment but is always added to the annotations.map file by some Symfony default behaviors, + * and you always end up with a not found Annotation. + */ + } foreach ($reflectionClass->getMethods() as $reflectionMethod) { - $reader->getMethodAnnotations($reflectionMethod); + try { + $reader->getMethodAnnotations($reflectionMethod); + } catch (AnnotationException $e) { + } } foreach ($reflectionClass->getProperties() as $reflectionProperty) { - $reader->getPropertyAnnotations($reflectionProperty); + try { + $reader->getPropertyAnnotations($reflectionProperty); + } catch (AnnotationException $e) { + } } } } diff --git a/lib/symfony/framework-bundle/CacheWarmer/SerializerCacheWarmer.php b/lib/symfony/framework-bundle/CacheWarmer/SerializerCacheWarmer.php index 917ea4723..e74206c86 100644 --- a/lib/symfony/framework-bundle/CacheWarmer/SerializerCacheWarmer.php +++ b/lib/symfony/framework-bundle/CacheWarmer/SerializerCacheWarmer.php @@ -56,10 +56,10 @@ class SerializerCacheWarmer extends AbstractPhpFileCacheWarmer foreach ($loader->getMappedClasses() as $mappedClass) { try { $metadataFactory->getMetadataFor($mappedClass); - } catch (\ReflectionException $e) { - // ignore failing reflection } catch (AnnotationException $e) { // ignore failing annotations + } catch (\Exception $e) { + $this->ignoreAutoloadException($mappedClass, $e); } } } diff --git a/lib/symfony/framework-bundle/CacheWarmer/ValidatorCacheWarmer.php b/lib/symfony/framework-bundle/CacheWarmer/ValidatorCacheWarmer.php index 8ac38133c..93c9eda6f 100644 --- a/lib/symfony/framework-bundle/CacheWarmer/ValidatorCacheWarmer.php +++ b/lib/symfony/framework-bundle/CacheWarmer/ValidatorCacheWarmer.php @@ -33,9 +33,8 @@ class ValidatorCacheWarmer extends AbstractPhpFileCacheWarmer private $validatorBuilder; /** - * @param ValidatorBuilderInterface $validatorBuilder - * @param string $phpArrayFile The PHP file where metadata are cached - * @param CacheItemPoolInterface $fallbackPool The pool where runtime-discovered metadata are cached + * @param string $phpArrayFile The PHP file where metadata are cached + * @param CacheItemPoolInterface $fallbackPool The pool where runtime-discovered metadata are cached */ public function __construct(ValidatorBuilderInterface $validatorBuilder, $phpArrayFile, CacheItemPoolInterface $fallbackPool) { @@ -61,10 +60,10 @@ class ValidatorCacheWarmer extends AbstractPhpFileCacheWarmer if ($metadataFactory->hasMetadataFor($mappedClass)) { $metadataFactory->getMetadataFor($mappedClass); } - } catch (\ReflectionException $e) { - // ignore failing reflection } catch (AnnotationException $e) { // ignore failing annotations + } catch (\Exception $e) { + $this->ignoreAutoloadException($mappedClass, $e); } } } diff --git a/lib/symfony/framework-bundle/Command/AboutCommand.php b/lib/symfony/framework-bundle/Command/AboutCommand.php index ad1590edf..e40114abe 100644 --- a/lib/symfony/framework-bundle/Command/AboutCommand.php +++ b/lib/symfony/framework-bundle/Command/AboutCommand.php @@ -123,7 +123,7 @@ EOT private static function isExpired($date) { - $date = \DateTime::createFromFormat('m/Y', $date); + $date = \DateTime::createFromFormat('d/m/Y', '01/'.$date); return false !== $date && new \DateTime() > $date->modify('last day of this month 23:59:59'); } diff --git a/lib/symfony/framework-bundle/Command/AbstractConfigCommand.php b/lib/symfony/framework-bundle/Command/AbstractConfigCommand.php index fe0d60b55..c03813397 100644 --- a/lib/symfony/framework-bundle/Command/AbstractConfigCommand.php +++ b/lib/symfony/framework-bundle/Command/AbstractConfigCommand.php @@ -14,6 +14,7 @@ namespace Symfony\Bundle\FrameworkBundle\Command; use Symfony\Component\Config\Definition\ConfigurationInterface; use Symfony\Component\Console\Exception\LogicException; use Symfony\Component\Console\Helper\Table; +use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\StyleInterface; use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; @@ -26,6 +27,9 @@ use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; */ abstract class AbstractConfigCommand extends ContainerDebugCommand { + /** + * @param OutputInterface|StyleInterface $output + */ protected function listBundles($output) { $title = 'Available registered bundles with their extension alias if available'; diff --git a/lib/symfony/framework-bundle/Command/CacheClearCommand.php b/lib/symfony/framework-bundle/Command/CacheClearCommand.php index 14f0dc28c..969ac030b 100644 --- a/lib/symfony/framework-bundle/Command/CacheClearCommand.php +++ b/lib/symfony/framework-bundle/Command/CacheClearCommand.php @@ -42,7 +42,6 @@ class CacheClearCommand extends ContainerAwareCommand /** * @param CacheClearerInterface $cacheClearer - * @param Filesystem|null $filesystem */ public function __construct($cacheClearer = null, Filesystem $filesystem = null) { @@ -267,10 +266,9 @@ EOF } /** - * @param KernelInterface $parent - * @param string $namespace - * @param string $parentClass - * @param string $warmupDir + * @param string $namespace + * @param string $parentClass + * @param string $warmupDir * * @return KernelInterface */ diff --git a/lib/symfony/framework-bundle/Command/ConfigDebugCommand.php b/lib/symfony/framework-bundle/Command/ConfigDebugCommand.php index 6aa3fbf9b..9919e4657 100644 --- a/lib/symfony/framework-bundle/Command/ConfigDebugCommand.php +++ b/lib/symfony/framework-bundle/Command/ConfigDebugCommand.php @@ -104,7 +104,7 @@ EOF } catch (LogicException $e) { $errorIo->error($e->getMessage()); - return; + return 1; } $io->title(sprintf('Current configuration for "%s.%s"', $extensionAlias, $path)); diff --git a/lib/symfony/framework-bundle/Command/ConfigDumpReferenceCommand.php b/lib/symfony/framework-bundle/Command/ConfigDumpReferenceCommand.php index 37b179899..a4d2764b1 100644 --- a/lib/symfony/framework-bundle/Command/ConfigDumpReferenceCommand.php +++ b/lib/symfony/framework-bundle/Command/ConfigDumpReferenceCommand.php @@ -86,7 +86,7 @@ EOF 'For dumping a specific option, add its path as the second argument of this command. (e.g. config:dump-reference FrameworkBundle profiler.matcher to dump the framework.profiler.matcher configuration)', ]); - return; + return null; } $extension = $this->findExtension($name); @@ -129,5 +129,7 @@ EOF } $io->writeln(null === $path ? $dumper->dump($configuration, $extension->getNamespace()) : $dumper->dumpAtPath($configuration, $path)); + + return null; } } diff --git a/lib/symfony/framework-bundle/Command/DebugAutowiringCommand.php b/lib/symfony/framework-bundle/Command/DebugAutowiringCommand.php index 72ac54856..84c87521c 100644 --- a/lib/symfony/framework-bundle/Command/DebugAutowiringCommand.php +++ b/lib/symfony/framework-bundle/Command/DebugAutowiringCommand.php @@ -93,5 +93,7 @@ EOF } $io->table([], $tableRows); + + return null; } } diff --git a/lib/symfony/framework-bundle/Command/RouterDebugCommand.php b/lib/symfony/framework-bundle/Command/RouterDebugCommand.php index b428b9e45..7ef645542 100644 --- a/lib/symfony/framework-bundle/Command/RouterDebugCommand.php +++ b/lib/symfony/framework-bundle/Command/RouterDebugCommand.php @@ -154,10 +154,13 @@ EOF } } + /** + * @return callable|null + */ private function extractCallable(Route $route) { if (!$route->hasDefault('_controller')) { - return; + return null; } $controller = $route->getDefault('_controller'); @@ -178,5 +181,7 @@ EOF return $controller; } catch (\InvalidArgumentException $e) { } + + return null; } } diff --git a/lib/symfony/framework-bundle/Command/RouterMatchCommand.php b/lib/symfony/framework-bundle/Command/RouterMatchCommand.php index 972c055bd..d6a1df8a0 100644 --- a/lib/symfony/framework-bundle/Command/RouterMatchCommand.php +++ b/lib/symfony/framework-bundle/Command/RouterMatchCommand.php @@ -149,5 +149,7 @@ EOF return 1; } + + return null; } } diff --git a/lib/symfony/framework-bundle/Command/TranslationUpdateCommand.php b/lib/symfony/framework-bundle/Command/TranslationUpdateCommand.php index 2a06b102e..7375450d5 100644 --- a/lib/symfony/framework-bundle/Command/TranslationUpdateCommand.php +++ b/lib/symfony/framework-bundle/Command/TranslationUpdateCommand.php @@ -242,7 +242,7 @@ EOF if (!\count($operation->getDomains())) { $errorIo->warning('No translation messages were found.'); - return; + return null; } $resultMessage = 'Translation files were successfully updated'; @@ -307,6 +307,8 @@ EOF } $errorIo->success($resultMessage.'.'); + + return null; } private function filterCatalogue(MessageCatalogue $catalogue, $domain) diff --git a/lib/symfony/framework-bundle/Console/Descriptor/Descriptor.php b/lib/symfony/framework-bundle/Console/Descriptor/Descriptor.php index c7b669fda..23d9ccc77 100644 --- a/lib/symfony/framework-bundle/Console/Descriptor/Descriptor.php +++ b/lib/symfony/framework-bundle/Console/Descriptor/Descriptor.php @@ -127,8 +127,6 @@ abstract class Descriptor implements DescriptorInterface * * name: name of described service * * @param Definition|Alias|object $service - * @param array $options - * @param ContainerBuilder|null $builder */ abstract protected function describeContainerService($service, array $options = [], ContainerBuilder $builder = null); @@ -166,8 +164,7 @@ abstract class Descriptor implements DescriptorInterface /** * Describes a callable. * - * @param callable $callable - * @param array $options + * @param mixed $callable */ abstract protected function describeCallable($callable, array $options = []); @@ -214,8 +211,7 @@ abstract class Descriptor implements DescriptorInterface } /** - * @param ContainerBuilder $builder - * @param string $serviceId + * @param string $serviceId * * @return mixed */ @@ -235,8 +231,7 @@ abstract class Descriptor implements DescriptorInterface } /** - * @param ContainerBuilder $builder - * @param bool $showPrivate + * @param bool $showPrivate * * @return array */ diff --git a/lib/symfony/framework-bundle/Console/Descriptor/JsonDescriptor.php b/lib/symfony/framework-bundle/Console/Descriptor/JsonDescriptor.php index c18d27868..ea5d0c7d0 100644 --- a/lib/symfony/framework-bundle/Console/Descriptor/JsonDescriptor.php +++ b/lib/symfony/framework-bundle/Console/Descriptor/JsonDescriptor.php @@ -142,7 +142,9 @@ class JsonDescriptor extends Descriptor protected function describeContainerAlias(Alias $alias, array $options = [], ContainerBuilder $builder = null) { if (!$builder) { - return $this->writeData($this->getContainerAliasData($alias), $options); + $this->writeData($this->getContainerAliasData($alias), $options); + + return; } $this->writeData( @@ -179,8 +181,6 @@ class JsonDescriptor extends Descriptor /** * Writes data as json. - * - * @return array|string */ private function writeData(array $data, array $options) { @@ -209,8 +209,7 @@ class JsonDescriptor extends Descriptor } /** - * @param Definition $definition - * @param bool $omitTags + * @param bool $omitTags * * @return array */ @@ -287,8 +286,7 @@ class JsonDescriptor extends Descriptor } /** - * @param EventDispatcherInterface $eventDispatcher - * @param string|null $event + * @param string|null $event * * @return array */ @@ -320,7 +318,6 @@ class JsonDescriptor extends Descriptor /** * @param callable $callable - * @param array $options * * @return array */ diff --git a/lib/symfony/framework-bundle/Console/Descriptor/MarkdownDescriptor.php b/lib/symfony/framework-bundle/Console/Descriptor/MarkdownDescriptor.php index 6575b05ec..2c31bdc19 100644 --- a/lib/symfony/framework-bundle/Console/Descriptor/MarkdownDescriptor.php +++ b/lib/symfony/framework-bundle/Console/Descriptor/MarkdownDescriptor.php @@ -249,7 +249,9 @@ class MarkdownDescriptor extends Descriptor ."\n".'- Public: '.($alias->isPublic() && !$alias->isPrivate() ? 'yes' : 'no'); if (!isset($options['id'])) { - return $this->write($output); + $this->write($output); + + return; } $this->write(sprintf("### %s\n\n%s\n", $options['id'], $output)); diff --git a/lib/symfony/framework-bundle/Console/Descriptor/TextDescriptor.php b/lib/symfony/framework-bundle/Console/Descriptor/TextDescriptor.php index 911e60c08..f17a1bba2 100644 --- a/lib/symfony/framework-bundle/Console/Descriptor/TextDescriptor.php +++ b/lib/symfony/framework-bundle/Console/Descriptor/TextDescriptor.php @@ -369,7 +369,7 @@ class TextDescriptor extends Descriptor return; } - return $this->describeContainerDefinition($builder->getDefinition((string) $alias), array_merge($options, ['id' => (string) $alias])); + $this->describeContainerDefinition($builder->getDefinition((string) $alias), array_merge($options, ['id' => (string) $alias])); } /** @@ -425,7 +425,6 @@ class TextDescriptor extends Descriptor $tableHeaders = ['Order', 'Callable', 'Priority']; $tableRows = []; - $order = 1; foreach ($eventListeners as $order => $listener) { $tableRows[] = [sprintf('#%d', $order + 1), $this->formatCallable($listener), $eventDispatcher->getListenerPriority($event, $listener)]; } @@ -434,8 +433,6 @@ class TextDescriptor extends Descriptor } /** - * @param array $config - * * @return string */ private function formatRouterConfig(array $config) @@ -494,7 +491,6 @@ class TextDescriptor extends Descriptor /** * @param string $content - * @param array $options */ private function writeText($content, array $options = []) { diff --git a/lib/symfony/framework-bundle/Console/Descriptor/XmlDescriptor.php b/lib/symfony/framework-bundle/Console/Descriptor/XmlDescriptor.php index 53e2ee1fa..96b9a261a 100644 --- a/lib/symfony/framework-bundle/Console/Descriptor/XmlDescriptor.php +++ b/lib/symfony/framework-bundle/Console/Descriptor/XmlDescriptor.php @@ -98,7 +98,9 @@ class XmlDescriptor extends Descriptor $dom->appendChild($dom->importNode($this->getContainerAliasDocument($alias, isset($options['id']) ? $options['id'] : null)->childNodes->item(0), true)); if (!$builder) { - return $this->writeDocument($dom); + $this->writeDocument($dom); + + return; } $dom->appendChild($dom->importNode($this->getContainerDefinitionDocument($builder->getDefinition((string) $alias), (string) $alias)->childNodes->item(0), true)); @@ -132,8 +134,6 @@ class XmlDescriptor extends Descriptor /** * Writes DOM document. - * - * @return \DOMDocument|string */ private function writeDocument(\DOMDocument $dom) { @@ -158,7 +158,6 @@ class XmlDescriptor extends Descriptor } /** - * @param Route $route * @param string|null $name * * @return \DOMDocument @@ -244,8 +243,7 @@ class XmlDescriptor extends Descriptor } /** - * @param ContainerBuilder $builder - * @param bool $showPrivate + * @param bool $showPrivate * * @return \DOMDocument */ @@ -268,10 +266,9 @@ class XmlDescriptor extends Descriptor } /** - * @param mixed $service - * @param string $id - * @param ContainerBuilder|null $builder - * @param bool $showArguments + * @param mixed $service + * @param string $id + * @param bool $showArguments * * @return \DOMDocument */ @@ -296,11 +293,10 @@ class XmlDescriptor extends Descriptor } /** - * @param ContainerBuilder $builder - * @param string|null $tag - * @param bool $showPrivate - * @param bool $showArguments - * @param callable $filter + * @param string|null $tag + * @param bool $showPrivate + * @param bool $showArguments + * @param callable $filter * * @return \DOMDocument */ @@ -330,7 +326,6 @@ class XmlDescriptor extends Descriptor } /** - * @param Definition $definition * @param string|null $id * @param bool $omitTags * @@ -454,7 +449,6 @@ class XmlDescriptor extends Descriptor } /** - * @param Alias $alias * @param string|null $id * * @return \DOMDocument @@ -492,8 +486,7 @@ class XmlDescriptor extends Descriptor } /** - * @param EventDispatcherInterface $eventDispatcher - * @param string|null $event + * @param string|null $event * * @return \DOMDocument */ diff --git a/lib/symfony/framework-bundle/Controller/ControllerTrait.php b/lib/symfony/framework-bundle/Controller/ControllerTrait.php index 78e2bd600..cb339cd15 100644 --- a/lib/symfony/framework-bundle/Controller/ControllerTrait.php +++ b/lib/symfony/framework-bundle/Controller/ControllerTrait.php @@ -431,7 +431,7 @@ trait ControllerTrait /** * Get a user from the Security Token Storage. * - * @return mixed + * @return object|null * * @throws \LogicException If SecurityBundle is not available * @@ -446,12 +446,12 @@ trait ControllerTrait } if (null === $token = $this->container->get('security.token_storage')->getToken()) { - return; + return null; } if (!\is_object($user = $token->getUser())) { // e.g. anonymous authentication - return; + return null; } return $user; diff --git a/lib/symfony/framework-bundle/DependencyInjection/Configuration.php b/lib/symfony/framework-bundle/DependencyInjection/Configuration.php index 52369bbff..00316daf5 100644 --- a/lib/symfony/framework-bundle/DependencyInjection/Configuration.php +++ b/lib/symfony/framework-bundle/DependencyInjection/Configuration.php @@ -264,7 +264,7 @@ class Configuration implements ConfigurationInterface ->canBeEnabled() ->beforeNormalization() ->always(function ($v) { - if (true === $v['enabled']) { + if (\is_array($v) && true === $v['enabled']) { $workflows = $v; unset($workflows['enabled']); @@ -470,12 +470,6 @@ class Configuration implements ConfigurationInterface $rootNode ->children() ->arrayNode('session') - ->validate() - ->ifTrue(function ($v) { - return empty($v['handler_id']) && !empty($v['save_path']); - }) - ->thenInvalid('Session save path is ignored without a handler service') - ->end() ->info('session configuration') ->canBeEnabled() ->children() @@ -504,7 +498,7 @@ class Configuration implements ConfigurationInterface ->defaultTrue() ->setDeprecated('The "%path%.%node%" option is enabled by default and deprecated since Symfony 3.4. It will be always enabled in 4.0.') ->end() - ->scalarNode('save_path')->end() + ->scalarNode('save_path')->defaultValue('%kernel.cache_dir%/sessions')->end() ->integerNode('metadata_update_threshold') ->defaultValue('0') ->info('seconds to wait between 2 session metadata updates') @@ -935,7 +929,11 @@ class Configuration implements ConfigurationInterface ->ifString()->then(function ($v) { return ['enabled' => true, 'resources' => $v]; }) ->end() ->beforeNormalization() - ->ifTrue(function ($v) { return \is_array($v) && !isset($v['resources']); }) + ->ifTrue(function ($v) { return \is_array($v) && !isset($v['enabled']); }) + ->then(function ($v) { return $v + ['enabled' => true]; }) + ->end() + ->beforeNormalization() + ->ifTrue(function ($v) { return \is_array($v) && !isset($v['resources']) && !isset($v['resource']); }) ->then(function ($v) { $e = $v['enabled']; unset($v['enabled']); @@ -954,7 +952,19 @@ class Configuration implements ConfigurationInterface ->end() ->beforeNormalization() ->ifTrue(function ($v) { return \is_array($v) && array_keys($v) === range(0, \count($v) - 1); }) - ->then(function ($v) { return ['default' => $v]; }) + ->then(function ($v) { + $resources = []; + foreach ($v as $resource) { + $resources = array_merge_recursive( + $resources, + \is_array($resource) && isset($resource['name']) + ? [$resource['name'] => $resource['value']] + : ['default' => $resource] + ); + } + + return $resources; + }) ->end() ->prototype('array') ->beforeNormalization()->ifString()->then(function ($v) { return [$v]; })->end() diff --git a/lib/symfony/framework-bundle/DependencyInjection/FrameworkExtension.php b/lib/symfony/framework-bundle/DependencyInjection/FrameworkExtension.php index 8243ac65f..3e28e52ad 100644 --- a/lib/symfony/framework-bundle/DependencyInjection/FrameworkExtension.php +++ b/lib/symfony/framework-bundle/DependencyInjection/FrameworkExtension.php @@ -234,7 +234,7 @@ class FrameworkExtension extends Extension if ($this->isConfigEnabled($container, $config['session'])) { if (!\extension_loaded('session')) { - throw new LogicException('Session support cannot be enabled as the session extension is not installed. See https://www.php.net/session.installation for instructions.'); + throw new LogicException('Session support cannot be enabled as the session extension is not installed. See https://php.net/session.installation for instructions.'); } $this->sessionConfigEnabled = true; @@ -877,11 +877,6 @@ class FrameworkExtension extends Extension // session handler (the internal callback registered with PHP session management) if (null === $config['handler_id']) { - // If the user set a save_path without using a non-default \SessionHandler, it will silently be ignored - if (isset($config['save_path'])) { - throw new LogicException('Session save path is ignored without a handler service'); - } - // Set the handler class to be null $container->getDefinition('session.storage.native')->replaceArgument(1, null); $container->getDefinition('session.storage.php_bridge')->replaceArgument(0, null); @@ -889,10 +884,6 @@ class FrameworkExtension extends Extension $container->setAlias('session.handler', $config['handler_id'])->setPrivate(true); } - if (!isset($config['save_path'])) { - $config['save_path'] = ini_get('session.save_path'); - } - $container->setParameter('session.save_path', $config['save_path']); if (\PHP_VERSION_ID < 70000) { @@ -1052,8 +1043,6 @@ class FrameworkExtension extends Extension $container->getDefinition('assets.url_package')->setPrivate(true); $container->getDefinition('assets.static_version_strategy')->setPrivate(true); - $defaultVersion = null; - if ($config['version_strategy']) { $defaultVersion = new Reference($config['version_strategy']); } else { @@ -1752,9 +1741,7 @@ class FrameworkExtension extends Extension } /** - * Returns the base path for the XSD files. - * - * @return string The XSD base path + * {@inheritdoc} */ public function getXsdValidationBasePath() { diff --git a/lib/symfony/framework-bundle/EventListener/SessionListener.php b/lib/symfony/framework-bundle/EventListener/SessionListener.php index aa5b4ba68..dc47013b1 100644 --- a/lib/symfony/framework-bundle/EventListener/SessionListener.php +++ b/lib/symfony/framework-bundle/EventListener/SessionListener.php @@ -34,10 +34,6 @@ class SessionListener extends AbstractSessionListener protected function getSession() { - if (!$this->container->has('session')) { - return; - } - - return $this->container->get('session'); + return $this->container->get('session', ContainerInterface::NULL_ON_INVALID_REFERENCE); } } diff --git a/lib/symfony/framework-bundle/EventListener/TestSessionListener.php b/lib/symfony/framework-bundle/EventListener/TestSessionListener.php index 55356be04..0e94341e7 100644 --- a/lib/symfony/framework-bundle/EventListener/TestSessionListener.php +++ b/lib/symfony/framework-bundle/EventListener/TestSessionListener.php @@ -34,10 +34,6 @@ class TestSessionListener extends AbstractTestSessionListener protected function getSession() { - if (!$this->container->has('session')) { - return; - } - - return $this->container->get('session'); + return $this->container->get('session', ContainerInterface::NULL_ON_INVALID_REFERENCE); } } diff --git a/lib/symfony/framework-bundle/Kernel/MicroKernelTrait.php b/lib/symfony/framework-bundle/Kernel/MicroKernelTrait.php index a8f3ce954..3779792d6 100644 --- a/lib/symfony/framework-bundle/Kernel/MicroKernelTrait.php +++ b/lib/symfony/framework-bundle/Kernel/MicroKernelTrait.php @@ -29,8 +29,6 @@ trait MicroKernelTrait * * $routes->import('config/routing.yml'); * $routes->add('/admin', 'AppBundle:Admin:dashboard', 'admin_dashboard'); - * - * @param RouteCollectionBuilder $routes */ abstract protected function configureRoutes(RouteCollectionBuilder $routes); @@ -50,9 +48,6 @@ trait MicroKernelTrait * Or parameters: * * $c->setParameter('halloween', 'lot of fun'); - * - * @param ContainerBuilder $c - * @param LoaderInterface $loader */ abstract protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader); diff --git a/lib/symfony/framework-bundle/Resources/config/annotations.xml b/lib/symfony/framework-bundle/Resources/config/annotations.xml index 02104ba26..9403917ff 100644 --- a/lib/symfony/framework-bundle/Resources/config/annotations.xml +++ b/lib/symfony/framework-bundle/Resources/config/annotations.xml @@ -37,7 +37,7 @@ %kernel.cache_dir%/annotations.php - #^Symfony\\(?:Component\\HttpKernel\\|Bundle\\FrameworkBundle\\Controller\\(?!AbstractController$|Controller$))# + #^Symfony\\(?:Component\\HttpKernel\\|Bundle\\FrameworkBundle\\Controller\\(?!.*Controller$))# %kernel.debug% diff --git a/lib/symfony/framework-bundle/Routing/Router.php b/lib/symfony/framework-bundle/Routing/Router.php index a846536a4..ebb5e145c 100644 --- a/lib/symfony/framework-bundle/Routing/Router.php +++ b/lib/symfony/framework-bundle/Routing/Router.php @@ -147,7 +147,7 @@ class Router extends BaseRouter implements WarmableInterface, ServiceSubscriberI return '%%'; } - if (preg_match('/^env\(\w+\)$/', $match[1])) { + if (preg_match('/^env\((?:\w++:)*+\w++\)$/', $match[1])) { throw new RuntimeException(sprintf('Using "%%%s%%" is not allowed in routing configuration.', $match[1])); } @@ -156,7 +156,7 @@ class Router extends BaseRouter implements WarmableInterface, ServiceSubscriberI if (\is_string($resolved) || is_numeric($resolved)) { $this->collectedParameters[$match[1]] = $resolved; - return (string) $resolved; + return (string) $this->resolve($resolved); } throw new RuntimeException(sprintf('The container parameter "%s", used in the route configuration value "%s", must be a string or numeric, but it is of type %s.', $match[1], $value, \gettype($resolved))); diff --git a/lib/symfony/framework-bundle/Templating/GlobalVariables.php b/lib/symfony/framework-bundle/Templating/GlobalVariables.php index 4e07b9b5b..ad5aee77f 100644 --- a/lib/symfony/framework-bundle/Templating/GlobalVariables.php +++ b/lib/symfony/framework-bundle/Templating/GlobalVariables.php @@ -36,7 +36,7 @@ class GlobalVariables public function getToken() { if (!$this->container->has('security.token_storage')) { - return; + return null; } return $this->container->get('security.token_storage')->getToken(); @@ -45,15 +45,12 @@ class GlobalVariables public function getUser() { if (!$token = $this->getToken()) { - return; + return null; } $user = $token->getUser(); - if (!\is_object($user)) { - return; - } - return $user; + return \is_object($user) ? $user : null; } /** @@ -61,9 +58,7 @@ class GlobalVariables */ public function getRequest() { - if ($this->container->has('request_stack')) { - return $this->container->get('request_stack')->getCurrentRequest(); - } + return $this->container->has('request_stack') ? $this->container->get('request_stack')->getCurrentRequest() : null; } /** @@ -71,9 +66,7 @@ class GlobalVariables */ public function getSession() { - if ($request = $this->getRequest()) { - return $request->getSession(); - } + return ($request = $this->getRequest()) ? $request->getSession() : null; } /** diff --git a/lib/symfony/framework-bundle/Templating/Helper/CodeHelper.php b/lib/symfony/framework-bundle/Templating/Helper/CodeHelper.php index c8914c3a5..a0a77f8d1 100644 --- a/lib/symfony/framework-bundle/Templating/Helper/CodeHelper.php +++ b/lib/symfony/framework-bundle/Templating/Helper/CodeHelper.php @@ -110,7 +110,7 @@ class CodeHelper extends Helper * @param string $file A file path * @param int $line The selected line number * - * @return string An HTML string + * @return string|null An HTML string */ public function fileExcerpt($file, $line) { @@ -120,12 +120,12 @@ class CodeHelper extends Helper // Check if the file is an application/octet-stream (eg. Phar file) because highlight_file cannot parse these files if ('application/octet-stream' === $finfo->file($file, FILEINFO_MIME_TYPE)) { - return; + return ''; } } // highlight_file could throw warnings - // see https://bugs.php.net/bug.php?id=25725 + // see https://bugs.php.net/25725 $code = @highlight_file($file, true); // remove main code/span tags $code = preg_replace('#^\s*(.*)\s*#s', '\\1', $code); @@ -138,6 +138,8 @@ class CodeHelper extends Helper return '
    '.implode("\n", $lines).'
'; } + + return null; } /** diff --git a/lib/symfony/framework-bundle/Templating/Helper/StopwatchHelper.php b/lib/symfony/framework-bundle/Templating/Helper/StopwatchHelper.php index 55232c462..2964cd35b 100644 --- a/lib/symfony/framework-bundle/Templating/Helper/StopwatchHelper.php +++ b/lib/symfony/framework-bundle/Templating/Helper/StopwatchHelper.php @@ -35,12 +35,14 @@ class StopwatchHelper extends Helper public function __call($method, $arguments = []) { - if (null !== $this->stopwatch) { - if (method_exists($this->stopwatch, $method)) { - return \call_user_func_array([$this->stopwatch, $method], $arguments); - } - - throw new \BadMethodCallException(sprintf('Method "%s" of Stopwatch does not exist', $method)); + if (null === $this->stopwatch) { + return null; } + + if (method_exists($this->stopwatch, $method)) { + return \call_user_func_array([$this->stopwatch, $method], $arguments); + } + + throw new \BadMethodCallException(sprintf('Method "%s" of Stopwatch does not exist', $method)); } } diff --git a/lib/symfony/framework-bundle/Test/KernelShutdownOnTearDownTrait.php b/lib/symfony/framework-bundle/Test/KernelShutdownOnTearDownTrait.php deleted file mode 100644 index b01dbb049..000000000 --- a/lib/symfony/framework-bundle/Test/KernelShutdownOnTearDownTrait.php +++ /dev/null @@ -1,47 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\FrameworkBundle\Test; - -use PHPUnit\Framework\TestCase; - -// Auto-adapt to PHPUnit 8 that added a `void` return-type to the tearDown method - -if (method_exists(\ReflectionMethod::class, 'hasReturnType') && (new \ReflectionMethod(TestCase::class, 'tearDown'))->hasReturnType()) { - eval(' - namespace Symfony\Bundle\FrameworkBundle\Test; - - /** - * @internal - */ - trait KernelShutdownOnTearDownTrait - { - protected function tearDown(): void - { - static::ensureKernelShutdown(); - } - } -'); -} else { - /** - * @internal - */ - trait KernelShutdownOnTearDownTrait - { - /** - * @return void - */ - protected function tearDown() - { - static::ensureKernelShutdown(); - } - } -} diff --git a/lib/symfony/framework-bundle/Test/KernelTestCase.php b/lib/symfony/framework-bundle/Test/KernelTestCase.php index 978f65863..92e92c0fe 100644 --- a/lib/symfony/framework-bundle/Test/KernelTestCase.php +++ b/lib/symfony/framework-bundle/Test/KernelTestCase.php @@ -23,7 +23,7 @@ use Symfony\Component\HttpKernel\KernelInterface; */ abstract class KernelTestCase extends TestCase { - use KernelShutdownOnTearDownTrait; + use ForwardCompatTestTrait; protected static $class; @@ -32,6 +32,12 @@ abstract class KernelTestCase extends TestCase */ protected static $kernel; + private function doTearDown() + { + static::ensureKernelShutdown(); + static::$kernel = null; + } + /** * Finds the directory where the phpunit.xml(.dist) is stored. * diff --git a/lib/symfony/framework-bundle/Tests/CacheWarmer/AnnotationsCacheWarmerTest.php b/lib/symfony/framework-bundle/Tests/CacheWarmer/AnnotationsCacheWarmerTest.php index 9cc3bfa2d..6ead6d746 100644 --- a/lib/symfony/framework-bundle/Tests/CacheWarmer/AnnotationsCacheWarmerTest.php +++ b/lib/symfony/framework-bundle/Tests/CacheWarmer/AnnotationsCacheWarmerTest.php @@ -5,6 +5,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\CacheWarmer; use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\CachedReader; use Doctrine\Common\Annotations\Reader; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Bundle\FrameworkBundle\CacheWarmer\AnnotationsCacheWarmer; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; use Symfony\Component\Cache\Adapter\ArrayAdapter; @@ -86,7 +87,55 @@ class AnnotationsCacheWarmerTest extends TestCase } /** - * @return \PHPUnit_Framework_MockObject_MockObject|Reader + * Test that the cache warming process is not broken if a class loader + * throws an exception (on class / file not found for example). + */ + public function testClassAutoloadException() + { + $this->assertFalse(class_exists($annotatedClass = 'C\C\C', false)); + + file_put_contents($this->cacheDir.'/annotations.map', sprintf('cacheDir, __FUNCTION__), new ArrayAdapter()); + + spl_autoload_register($classLoader = function ($class) use ($annotatedClass) { + if ($class === $annotatedClass) { + throw new \DomainException('This exception should be caught by the warmer.'); + } + }, true, true); + + $warmer->warmUp($this->cacheDir); + + spl_autoload_unregister($classLoader); + } + + /** + * Test that the cache warming process is broken if a class loader throws an + * exception but that is unrelated to the class load. + */ + public function testClassAutoloadExceptionWithUnrelatedException() + { + $this->expectException(\DomainException::class); + $this->expectExceptionMessage('This exception should not be caught by the warmer.'); + + $this->assertFalse(class_exists($annotatedClass = 'AClassThatDoesNotExist_FWB_CacheWarmer_AnnotationsCacheWarmerTest', false)); + + file_put_contents($this->cacheDir.'/annotations.map', sprintf('cacheDir, __FUNCTION__), new ArrayAdapter()); + + spl_autoload_register($classLoader = function ($class) use ($annotatedClass) { + if ($class === $annotatedClass) { + eval('class '.$annotatedClass.'{}'); + throw new \DomainException('This exception should not be caught by the warmer.'); + } + }, true, true); + + $warmer->warmUp($this->cacheDir); + + spl_autoload_unregister($classLoader); + } + + /** + * @return MockObject|Reader */ private function getReadOnlyReader() { diff --git a/lib/symfony/framework-bundle/Tests/CacheWarmer/SerializerCacheWarmerTest.php b/lib/symfony/framework-bundle/Tests/CacheWarmer/SerializerCacheWarmerTest.php index 50a5abf0a..1a244252f 100644 --- a/lib/symfony/framework-bundle/Tests/CacheWarmer/SerializerCacheWarmerTest.php +++ b/lib/symfony/framework-bundle/Tests/CacheWarmer/SerializerCacheWarmerTest.php @@ -50,7 +50,7 @@ class SerializerCacheWarmerTest extends TestCase $values = $fallbackPool->getValues(); - $this->assertInternalType('array', $values); + $this->assertIsArray($values); $this->assertCount(2, $values); $this->assertArrayHasKey('Symfony_Bundle_FrameworkBundle_Tests_Fixtures_Serialization_Person', $values); $this->assertArrayHasKey('Symfony_Bundle_FrameworkBundle_Tests_Fixtures_Serialization_Author', $values); @@ -74,7 +74,61 @@ class SerializerCacheWarmerTest extends TestCase $values = $fallbackPool->getValues(); - $this->assertInternalType('array', $values); + $this->assertIsArray($values); $this->assertCount(0, $values); } + + /** + * Test that the cache warming process is not broken if a class loader + * throws an exception (on class / file not found for example). + */ + public function testClassAutoloadException() + { + if (!class_exists(CacheClassMetadataFactory::class) || !method_exists(XmlFileLoader::class, 'getMappedClasses') || !method_exists(YamlFileLoader::class, 'getMappedClasses')) { + $this->markTestSkipped('The Serializer default cache warmer has been introduced in the Serializer Component version 3.2.'); + } + + $this->assertFalse(class_exists($mappedClass = 'AClassThatDoesNotExist_FWB_CacheWarmer_SerializerCacheWarmerTest', false)); + + $warmer = new SerializerCacheWarmer([new YamlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/does_not_exist.yaml')], tempnam(sys_get_temp_dir(), __FUNCTION__), new ArrayAdapter()); + + spl_autoload_register($classLoader = function ($class) use ($mappedClass) { + if ($class === $mappedClass) { + throw new \DomainException('This exception should be caught by the warmer.'); + } + }, true, true); + + $warmer->warmUp('foo'); + + spl_autoload_unregister($classLoader); + } + + /** + * Test that the cache warming process is broken if a class loader throws an + * exception but that is unrelated to the class load. + */ + public function testClassAutoloadExceptionWithUnrelatedException() + { + $this->expectException(\DomainException::class); + $this->expectExceptionMessage('This exception should not be caught by the warmer.'); + + if (!class_exists(CacheClassMetadataFactory::class) || !method_exists(XmlFileLoader::class, 'getMappedClasses') || !method_exists(YamlFileLoader::class, 'getMappedClasses')) { + $this->markTestSkipped('The Serializer default cache warmer has been introduced in the Serializer Component version 3.2.'); + } + + $this->assertFalse(class_exists($mappedClass = 'AClassThatDoesNotExist_FWB_CacheWarmer_SerializerCacheWarmerTest', false)); + + $warmer = new SerializerCacheWarmer([new YamlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/does_not_exist.yaml')], tempnam(sys_get_temp_dir(), __FUNCTION__), new ArrayAdapter()); + + spl_autoload_register($classLoader = function ($class) use ($mappedClass) { + if ($class === $mappedClass) { + eval('class '.$mappedClass.'{}'); + throw new \DomainException('This exception should not be caught by the warmer.'); + } + }, true, true); + + $warmer->warmUp('foo'); + + spl_autoload_unregister($classLoader); + } } diff --git a/lib/symfony/framework-bundle/Tests/CacheWarmer/ValidatorCacheWarmerTest.php b/lib/symfony/framework-bundle/Tests/CacheWarmer/ValidatorCacheWarmerTest.php index 47c88f1a2..33d114035 100644 --- a/lib/symfony/framework-bundle/Tests/CacheWarmer/ValidatorCacheWarmerTest.php +++ b/lib/symfony/framework-bundle/Tests/CacheWarmer/ValidatorCacheWarmerTest.php @@ -46,7 +46,7 @@ class ValidatorCacheWarmerTest extends TestCase $values = $fallbackPool->getValues(); - $this->assertInternalType('array', $values); + $this->assertIsArray($values); $this->assertCount(2, $values); $this->assertArrayHasKey('Symfony.Bundle.FrameworkBundle.Tests.Fixtures.Validation.Person', $values); $this->assertArrayHasKey('Symfony.Bundle.FrameworkBundle.Tests.Fixtures.Validation.Author', $values); @@ -77,7 +77,7 @@ class ValidatorCacheWarmerTest extends TestCase $values = $fallbackPool->getValues(); - $this->assertInternalType('array', $values); + $this->assertIsArray($values); $this->assertCount(2, $values); $this->assertArrayHasKey('Symfony.Bundle.FrameworkBundle.Tests.Fixtures.Validation.Category', $values); $this->assertArrayHasKey('Symfony.Bundle.FrameworkBundle.Tests.Fixtures.Validation.SubCategory', $values); @@ -99,7 +99,57 @@ class ValidatorCacheWarmerTest extends TestCase $values = $fallbackPool->getValues(); - $this->assertInternalType('array', $values); + $this->assertIsArray($values); $this->assertCount(0, $values); } + + /** + * Test that the cache warming process is not broken if a class loader + * throws an exception (on class / file not found for example). + */ + public function testClassAutoloadException() + { + $this->assertFalse(class_exists($mappedClass = 'AClassThatDoesNotExist_FWB_CacheWarmer_ValidatorCacheWarmerTest', false)); + + $validatorBuilder = new ValidatorBuilder(); + $validatorBuilder->addYamlMapping(__DIR__.'/../Fixtures/Validation/Resources/does_not_exist.yaml'); + $warmer = new ValidatorCacheWarmer($validatorBuilder, tempnam(sys_get_temp_dir(), __FUNCTION__), new ArrayAdapter()); + + spl_autoload_register($classloader = function ($class) use ($mappedClass) { + if ($class === $mappedClass) { + throw new \DomainException('This exception should be caught by the warmer.'); + } + }, true, true); + + $warmer->warmUp('foo'); + + spl_autoload_unregister($classloader); + } + + /** + * Test that the cache warming process is broken if a class loader throws an + * exception but that is unrelated to the class load. + */ + public function testClassAutoloadExceptionWithUnrelatedException() + { + $this->expectException(\DomainException::class); + $this->expectExceptionMessage('This exception should not be caught by the warmer.'); + + $this->assertFalse(class_exists($mappedClass = 'AClassThatDoesNotExist_FWB_CacheWarmer_ValidatorCacheWarmerTest', false)); + + $validatorBuilder = new ValidatorBuilder(); + $validatorBuilder->addYamlMapping(__DIR__.'/../Fixtures/Validation/Resources/does_not_exist.yaml'); + $warmer = new ValidatorCacheWarmer($validatorBuilder, tempnam(sys_get_temp_dir(), __FUNCTION__), new ArrayAdapter()); + + spl_autoload_register($classLoader = function ($class) use ($mappedClass) { + if ($class === $mappedClass) { + eval('class '.$mappedClass.'{}'); + throw new \DomainException('This exception should not be caught by the warmer.'); + } + }, true, true); + + $warmer->warmUp('foo'); + + spl_autoload_unregister($classLoader); + } } diff --git a/lib/symfony/framework-bundle/Tests/Command/CachePruneCommandTest.php b/lib/symfony/framework-bundle/Tests/Command/CachePruneCommandTest.php index 3a603122e..7ce554b3e 100644 --- a/lib/symfony/framework-bundle/Tests/Command/CachePruneCommandTest.php +++ b/lib/symfony/framework-bundle/Tests/Command/CachePruneCommandTest.php @@ -11,6 +11,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Command; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Bundle\FrameworkBundle\Command\CachePoolPruneCommand; use Symfony\Bundle\FrameworkBundle\Console\Application; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; @@ -55,7 +56,7 @@ class CachePruneCommandTest extends TestCase } /** - * @return \PHPUnit_Framework_MockObject_MockObject|KernelInterface + * @return MockObject|KernelInterface */ private function getKernel() { @@ -81,7 +82,7 @@ class CachePruneCommandTest extends TestCase } /** - * @return \PHPUnit_Framework_MockObject_MockObject|PruneableInterface + * @return MockObject|PruneableInterface */ private function getPruneableInterfaceMock() { diff --git a/lib/symfony/framework-bundle/Tests/Command/RouterDebugCommandTest.php b/lib/symfony/framework-bundle/Tests/Command/RouterDebugCommandTest.php index 4790f271d..a4842f239 100644 --- a/lib/symfony/framework-bundle/Tests/Command/RouterDebugCommandTest.php +++ b/lib/symfony/framework-bundle/Tests/Command/RouterDebugCommandTest.php @@ -27,7 +27,7 @@ class RouterDebugCommandTest extends TestCase $ret = $tester->execute(['name' => null], ['decorated' => false]); $this->assertEquals(0, $ret, 'Returns 0 in case of success'); - $this->assertContains('Name Method Scheme Host Path', $tester->getDisplay()); + $this->assertStringContainsString('Name Method Scheme Host Path', $tester->getDisplay()); } public function testDebugSingleRoute() @@ -36,14 +36,12 @@ class RouterDebugCommandTest extends TestCase $ret = $tester->execute(['name' => 'foo'], ['decorated' => false]); $this->assertEquals(0, $ret, 'Returns 0 in case of success'); - $this->assertContains('Route Name | foo', $tester->getDisplay()); + $this->assertStringContainsString('Route Name | foo', $tester->getDisplay()); } - /** - * @expectedException \InvalidArgumentException - */ public function testDebugInvalidRoute() { + $this->expectException('InvalidArgumentException'); $this->createCommandTester()->execute(['name' => 'test']); } diff --git a/lib/symfony/framework-bundle/Tests/Command/RouterMatchCommandTest.php b/lib/symfony/framework-bundle/Tests/Command/RouterMatchCommandTest.php index e0bc2de0e..b4748dde0 100644 --- a/lib/symfony/framework-bundle/Tests/Command/RouterMatchCommandTest.php +++ b/lib/symfony/framework-bundle/Tests/Command/RouterMatchCommandTest.php @@ -29,7 +29,7 @@ class RouterMatchCommandTest extends TestCase $ret = $tester->execute(['path_info' => '/foo', 'foo'], ['decorated' => false]); $this->assertEquals(0, $ret, 'Returns 0 in case of success'); - $this->assertContains('Route Name | foo', $tester->getDisplay()); + $this->assertStringContainsString('Route Name | foo', $tester->getDisplay()); } public function testWithNotMatchPath() @@ -38,7 +38,7 @@ class RouterMatchCommandTest extends TestCase $ret = $tester->execute(['path_info' => '/test', 'foo'], ['decorated' => false]); $this->assertEquals(1, $ret, 'Returns 1 in case of failure'); - $this->assertContains('None of the routes match the path "/test"', $tester->getDisplay()); + $this->assertStringContainsString('None of the routes match the path "/test"', $tester->getDisplay()); } /** @@ -56,7 +56,7 @@ class RouterMatchCommandTest extends TestCase $tester->execute(['path_info' => '/']); - $this->assertContains('None of the routes match the path "/"', $tester->getDisplay()); + $this->assertStringContainsString('None of the routes match the path "/"', $tester->getDisplay()); } /** diff --git a/lib/symfony/framework-bundle/Tests/Command/TranslationDebugCommandTest.php b/lib/symfony/framework-bundle/Tests/Command/TranslationDebugCommandTest.php index cfa6e3b8a..b3e849b13 100644 --- a/lib/symfony/framework-bundle/Tests/Command/TranslationDebugCommandTest.php +++ b/lib/symfony/framework-bundle/Tests/Command/TranslationDebugCommandTest.php @@ -94,11 +94,9 @@ class TranslationDebugCommandTest extends TestCase $this->assertRegExp('/unused/', $tester->getDisplay()); } - /** - * @expectedException \InvalidArgumentException - */ public function testDebugInvalidDirectory() { + $this->expectException('InvalidArgumentException'); $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock(); $kernel->expects($this->once()) ->method('getBundle') @@ -241,7 +239,7 @@ class TranslationDebugCommandTest extends TestCase $tester = new CommandTester($application->find('debug:translation')); $tester->execute(['locale' => 'en']); - $this->assertContains('No defined or extracted', $tester->getDisplay()); + $this->assertStringContainsString('No defined or extracted', $tester->getDisplay()); } private function getBundle($path) diff --git a/lib/symfony/framework-bundle/Tests/Command/TranslationUpdateCommandTest.php b/lib/symfony/framework-bundle/Tests/Command/TranslationUpdateCommandTest.php index 7e487ff52..8483f0f0d 100644 --- a/lib/symfony/framework-bundle/Tests/Command/TranslationUpdateCommandTest.php +++ b/lib/symfony/framework-bundle/Tests/Command/TranslationUpdateCommandTest.php @@ -231,7 +231,7 @@ class TranslationUpdateCommandTest extends TestCase $tester = new CommandTester($application->find('translation:update')); $tester->execute(['locale' => 'en']); - $this->assertContains('You must choose one of --force or --dump-messages', $tester->getDisplay()); + $this->assertStringContainsString('You must choose one of --force or --dump-messages', $tester->getDisplay()); } private function getBundle($path) diff --git a/lib/symfony/framework-bundle/Tests/Command/YamlLintCommandTest.php b/lib/symfony/framework-bundle/Tests/Command/YamlLintCommandTest.php index a71fb824d..ba883543c 100644 --- a/lib/symfony/framework-bundle/Tests/Command/YamlLintCommandTest.php +++ b/lib/symfony/framework-bundle/Tests/Command/YamlLintCommandTest.php @@ -41,7 +41,7 @@ class YamlLintCommandTest extends TestCase ); $this->assertEquals(0, $tester->getStatusCode(), 'Returns 0 in case of success'); - $this->assertContains('OK', trim($tester->getDisplay())); + $this->assertStringContainsString('OK', trim($tester->getDisplay())); } public function testLintIncorrectFile() @@ -55,14 +55,12 @@ bar'; $tester->execute(['filename' => $filename], ['decorated' => false]); $this->assertEquals(1, $tester->getStatusCode(), 'Returns 1 in case of error'); - $this->assertContains('Unable to parse at line 3 (near "bar").', trim($tester->getDisplay())); + $this->assertStringContainsString('Unable to parse at line 3 (near "bar").', trim($tester->getDisplay())); } - /** - * @expectedException \RuntimeException - */ public function testLintFileNotReadable() { + $this->expectException('RuntimeException'); $tester = $this->createCommandTester(); $filename = $this->createFile(''); unlink($filename); @@ -74,29 +72,12 @@ bar'; { $command = new YamlLintCommand(); $expected = <<%command.name% command lints a YAML file and outputs to STDOUT -the first encountered syntax error. - -You can validates YAML contents passed from STDIN: - - cat filename | php %command.full_name% - -You can also validate the syntax of a file: - - php %command.full_name% filename - -Or of a whole directory: - - php %command.full_name% dirname - php %command.full_name% dirname --format=json - Or find all files in a bundle: php %command.full_name% @AcmeDemoBundle - EOF; - $this->assertEquals($expected, $command->getHelp()); + $this->assertStringContainsString($expected, $command->getHelp()); } public function testLintFilesFromBundleDirectory() @@ -108,7 +89,7 @@ EOF; ); $this->assertEquals(0, $tester->getStatusCode(), 'Returns 0 in case of success'); - $this->assertContains('[OK] All 0 YAML files contain valid syntax', trim($tester->getDisplay())); + $this->assertStringContainsString('[OK] All 0 YAML files contain valid syntax', trim($tester->getDisplay())); } /** diff --git a/lib/symfony/framework-bundle/Tests/Console/ApplicationTest.php b/lib/symfony/framework-bundle/Tests/Console/ApplicationTest.php index fbc5a7733..50f9478cd 100644 --- a/lib/symfony/framework-bundle/Tests/Console/ApplicationTest.php +++ b/lib/symfony/framework-bundle/Tests/Console/ApplicationTest.php @@ -160,9 +160,9 @@ class ApplicationTest extends TestCase $output = $tester->getDisplay(); $this->assertSame(0, $tester->getStatusCode()); - $this->assertContains('Some commands could not be registered:', $output); - $this->assertContains('throwing', $output); - $this->assertContains('fine', $output); + $this->assertStringContainsString('Some commands could not be registered:', $output); + $this->assertStringContainsString('throwing', $output); + $this->assertStringContainsString('fine', $output); } public function testRegistrationErrorsAreDisplayedOnCommandNotFound() @@ -188,8 +188,8 @@ class ApplicationTest extends TestCase $output = $tester->getDisplay(); $this->assertSame(1, $tester->getStatusCode()); - $this->assertContains('Some commands could not be registered:', $output); - $this->assertContains('Command "fine" is not defined.', $output); + $this->assertStringContainsString('Some commands could not be registered:', $output); + $this->assertStringContainsString('Command "fine" is not defined.', $output); } private function getKernel(array $bundles, $useDispatcher = false) diff --git a/lib/symfony/framework-bundle/Tests/Controller/ControllerNameParserTest.php b/lib/symfony/framework-bundle/Tests/Controller/ControllerNameParserTest.php index 91a72821e..3d4a503f2 100644 --- a/lib/symfony/framework-bundle/Tests/Controller/ControllerNameParserTest.php +++ b/lib/symfony/framework-bundle/Tests/Controller/ControllerNameParserTest.php @@ -127,9 +127,9 @@ class ControllerNameParserTest extends TestCase if (false === $suggestedBundleName) { // make sure we don't have a suggestion - $this->assertNotContains('Did you mean', $e->getMessage()); + $this->assertStringNotContainsString('Did you mean', $e->getMessage()); } else { - $this->assertContains(sprintf('Did you mean "%s"', $suggestedBundleName), $e->getMessage()); + $this->assertStringContainsString(sprintf('Did you mean "%s"', $suggestedBundleName), $e->getMessage()); } } } diff --git a/lib/symfony/framework-bundle/Tests/Controller/ControllerTraitTest.php b/lib/symfony/framework-bundle/Tests/Controller/ControllerTraitTest.php index da950ce0c..c03934565 100644 --- a/lib/symfony/framework-bundle/Tests/Controller/ControllerTraitTest.php +++ b/lib/symfony/framework-bundle/Tests/Controller/ControllerTraitTest.php @@ -87,12 +87,10 @@ abstract class ControllerTraitTest extends TestCase $this->assertNull($controller->getUser()); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage The SecurityBundle is not registered in your application. - */ public function testGetUserWithEmptyContainer() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('The SecurityBundle is not registered in your application.'); $controller = $this->createController(); $controller->setContainer(new Container()); @@ -188,8 +186,8 @@ abstract class ControllerTraitTest extends TestCase if ($response->headers->get('content-type')) { $this->assertSame('text/x-php', $response->headers->get('content-type')); } - $this->assertContains(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); - $this->assertContains(basename(__FILE__), $response->headers->get('content-disposition')); + $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); + $this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition')); } public function testFileAsInline() @@ -204,8 +202,8 @@ abstract class ControllerTraitTest extends TestCase if ($response->headers->get('content-type')) { $this->assertSame('text/x-php', $response->headers->get('content-type')); } - $this->assertContains(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition')); - $this->assertContains(basename(__FILE__), $response->headers->get('content-disposition')); + $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition')); + $this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition')); } public function testFileWithOwnFileName() @@ -221,8 +219,8 @@ abstract class ControllerTraitTest extends TestCase if ($response->headers->get('content-type')) { $this->assertSame('text/x-php', $response->headers->get('content-type')); } - $this->assertContains(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); - $this->assertContains($fileName, $response->headers->get('content-disposition')); + $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); + $this->assertStringContainsString($fileName, $response->headers->get('content-disposition')); } public function testFileWithOwnFileNameAsInline() @@ -238,8 +236,8 @@ abstract class ControllerTraitTest extends TestCase if ($response->headers->get('content-type')) { $this->assertSame('text/x-php', $response->headers->get('content-type')); } - $this->assertContains(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition')); - $this->assertContains($fileName, $response->headers->get('content-disposition')); + $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition')); + $this->assertStringContainsString($fileName, $response->headers->get('content-disposition')); } public function testFileFromPath() @@ -254,8 +252,8 @@ abstract class ControllerTraitTest extends TestCase if ($response->headers->get('content-type')) { $this->assertSame('text/x-php', $response->headers->get('content-type')); } - $this->assertContains(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); - $this->assertContains(basename(__FILE__), $response->headers->get('content-disposition')); + $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); + $this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition')); } public function testFileFromPathWithCustomizedFileName() @@ -270,19 +268,16 @@ abstract class ControllerTraitTest extends TestCase if ($response->headers->get('content-type')) { $this->assertSame('text/x-php', $response->headers->get('content-type')); } - $this->assertContains(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); - $this->assertContains('test.php', $response->headers->get('content-disposition')); + $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); + $this->assertStringContainsString('test.php', $response->headers->get('content-disposition')); } - /** - * @expectedException \Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException - */ public function testFileWhichDoesNotExist() { + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); $controller = $this->createController(); - /* @var BinaryFileResponse $response */ - $response = $controller->file('some-file.txt', 'test.php'); + $controller->file('some-file.txt', 'test.php'); } public function testIsGranted() @@ -299,11 +294,9 @@ abstract class ControllerTraitTest extends TestCase $this->assertTrue($controller->isGranted('foo')); } - /** - * @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException - */ public function testdenyAccessUnlessGranted() { + $this->expectException('Symfony\Component\Security\Core\Exception\AccessDeniedException'); $authorizationChecker = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface')->getMock(); $authorizationChecker->expects($this->once())->method('isGranted')->willReturn(false); @@ -431,10 +424,10 @@ abstract class ControllerTraitTest extends TestCase public function testRedirect() { $controller = $this->createController(); - $response = $controller->redirect('http://dunglas.fr', 301); + $response = $controller->redirect('https://dunglas.fr', 301); $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); - $this->assertSame('http://dunglas.fr', $response->getTargetUrl()); + $this->assertSame('https://dunglas.fr', $response->getTargetUrl()); $this->assertSame(301, $response->getStatusCode()); } diff --git a/lib/symfony/framework-bundle/Tests/Controller/TemplateControllerTest.php b/lib/symfony/framework-bundle/Tests/Controller/TemplateControllerTest.php index 9dba1c05a..7b4ed8e51 100644 --- a/lib/symfony/framework-bundle/Tests/Controller/TemplateControllerTest.php +++ b/lib/symfony/framework-bundle/Tests/Controller/TemplateControllerTest.php @@ -77,12 +77,10 @@ class TemplateControllerTest extends TestCase $this->assertEquals('bar', $controller->templateAction('mytemplate')->getContent()); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage You can not use the TemplateController if the Templating Component or the Twig Bundle are not available. - */ public function testNoTwigNorTemplating() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('You can not use the TemplateController if the Templating Component or the Twig Bundle are not available.'); $controller = new TemplateController(); $controller->templateAction('mytemplate')->getContent(); diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/AddConsoleCommandPassTest.php b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/AddConsoleCommandPassTest.php index 3681ca204..16f0f68d2 100644 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/AddConsoleCommandPassTest.php +++ b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/AddConsoleCommandPassTest.php @@ -63,12 +63,10 @@ class AddConsoleCommandPassTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The service "my-command" tagged "console.command" must not be abstract. - */ public function testProcessThrowAnExceptionIfTheServiceIsAbstract() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The service "my-command" tagged "console.command" must not be abstract.'); $container = new ContainerBuilder(); $container->addCompilerPass(new AddConsoleCommandPass()); @@ -80,12 +78,10 @@ class AddConsoleCommandPassTest extends TestCase $container->compile(); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The service "my-command" tagged "console.command" must be a subclass of "Symfony\Component\Console\Command\Command". - */ public function testProcessThrowAnExceptionIfTheServiceIsNotASubclassOfCommand() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The service "my-command" tagged "console.command" must be a subclass of "Symfony\Component\Console\Command\Command".'); $container = new ContainerBuilder(); $container->addCompilerPass(new AddConsoleCommandPass()); diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/AddConstraintValidatorsPassTest.php b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/AddConstraintValidatorsPassTest.php index 6fdf8a51e..1d998395e 100644 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/AddConstraintValidatorsPassTest.php +++ b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/AddConstraintValidatorsPassTest.php @@ -46,14 +46,12 @@ class AddConstraintValidatorsPassTest extends TestCase $this->assertEquals($expected, $container->getDefinition((string) $validatorFactory->getArgument(0))); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The service "my_abstract_constraint_validator" tagged "validator.constraint_validator" must not be abstract. - */ public function testAbstractConstraintValidator() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The service "my_abstract_constraint_validator" tagged "validator.constraint_validator" must not be abstract.'); $container = new ContainerBuilder(); - $validatorFactory = $container->register('validator.validator_factory') + $container->register('validator.validator_factory') ->addArgument([]); $container->register('my_abstract_constraint_validator') diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/CachePoolPassTest.php b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/CachePoolPassTest.php index 1e7dc416c..53ea1bf68 100644 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/CachePoolPassTest.php +++ b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/CachePoolPassTest.php @@ -93,12 +93,10 @@ class CachePoolPassTest extends TestCase $this->assertSame(3, $cachePool->getArgument(2)); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid "cache.pool" tag for service "app.cache_pool": accepted attributes are - */ public function testThrowsExceptionWhenCachePoolTagHasUnknownAttributes() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Invalid "cache.pool" tag for service "app.cache_pool": accepted attributes are'); $container = new ContainerBuilder(); $container->setParameter('kernel.debug', false); $container->setParameter('kernel.name', 'app'); diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/CachePoolPrunerPassTest.php b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/CachePoolPrunerPassTest.php index 2ef2e1535..1439d36f8 100644 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/CachePoolPrunerPassTest.php +++ b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/CachePoolPrunerPassTest.php @@ -56,12 +56,10 @@ class CachePoolPrunerPassTest extends TestCase $this->assertCount($aliasesBefore, $container->getAliases()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Class "Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\NotFound" used for service "pool.not-found" cannot be found. - */ public function testCompilerPassThrowsOnInvalidDefinitionClass() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Class "Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\Compiler\NotFound" used for service "pool.not-found" cannot be found.'); $container = new ContainerBuilder(); $container->register('console.command.cache_pool_prune')->addArgument([]); $container->register('pool.not-found', NotFound::class)->addTag('cache.pool'); diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/FormPassTest.php b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/FormPassTest.php index b5e3c9f24..a73093e7c 100644 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/FormPassTest.php +++ b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/FormPassTest.php @@ -124,12 +124,10 @@ class FormPassTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage extended-type attribute, none was configured for the "my.type_extension" service - */ public function testAddTaggedFormTypeExtensionWithoutExtendedTypeAttribute() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('extended-type attribute, none was configured for the "my.type_extension" service'); $container = new ContainerBuilder(); $container->addCompilerPass(new FormPass()); diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/ProfilerPassTest.php b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/ProfilerPassTest.php index b693165f8..99299282a 100644 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/ProfilerPassTest.php +++ b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/ProfilerPassTest.php @@ -24,11 +24,10 @@ class ProfilerPassTest extends TestCase * Thus, a fully-valid tag looks something like this: * * - * - * @expectedException \InvalidArgumentException */ public function testTemplateNoIdThrowsException() { + $this->expectException('InvalidArgumentException'); $builder = new ContainerBuilder(); $builder->register('profiler', 'ProfilerClass'); $builder->register('my_collector_service') diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/SerializerPassTest.php b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/SerializerPassTest.php index e1a7b0be6..0bc621acb 100644 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/SerializerPassTest.php +++ b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/SerializerPassTest.php @@ -25,12 +25,10 @@ use Symfony\Component\DependencyInjection\Reference; */ class SerializerPassTest extends TestCase { - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage You must tag at least one service as "serializer.normalizer" to use the "serializer" service - */ public function testThrowExceptionWhenNoNormalizers() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('You must tag at least one service as "serializer.normalizer" to use the "serializer" service'); $container = new ContainerBuilder(); $container->register('serializer'); @@ -38,12 +36,10 @@ class SerializerPassTest extends TestCase $serializerPass->process($container); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage You must tag at least one service as "serializer.encoder" to use the "serializer" service - */ public function testThrowExceptionWhenNoEncoders() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('You must tag at least one service as "serializer.encoder" to use the "serializer" service'); $container = new ContainerBuilder(); $container->register('serializer') ->addArgument([]) diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php index 44c87b188..a267908ec 100644 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php +++ b/lib/symfony/framework-bundle/Tests/DependencyInjection/Compiler/WorkflowGuardListenerPassTest.php @@ -52,12 +52,10 @@ class WorkflowGuardListenerPassTest extends TestCase $this->assertFalse($this->container->hasParameter('workflow.has_guard_listeners')); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - * @expectedExceptionMessage The "security.token_storage" service is needed to be able to use the workflow guard listener. - */ public function testExceptionIfTheTokenStorageServiceIsNotPresent() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); + $this->expectExceptionMessage('The "security.token_storage" service is needed to be able to use the workflow guard listener.'); $this->container->setParameter('workflow.has_guard_listeners', true); $this->container->register('security.authorization_checker', AuthorizationCheckerInterface::class); $this->container->register('security.authentication.trust_resolver', AuthenticationTrustResolverInterface::class); @@ -66,12 +64,10 @@ class WorkflowGuardListenerPassTest extends TestCase $this->compilerPass->process($this->container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - * @expectedExceptionMessage The "security.authorization_checker" service is needed to be able to use the workflow guard listener. - */ public function testExceptionIfTheAuthorizationCheckerServiceIsNotPresent() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); + $this->expectExceptionMessage('The "security.authorization_checker" service is needed to be able to use the workflow guard listener.'); $this->container->setParameter('workflow.has_guard_listeners', true); $this->container->register('security.token_storage', TokenStorageInterface::class); $this->container->register('security.authentication.trust_resolver', AuthenticationTrustResolverInterface::class); @@ -80,12 +76,10 @@ class WorkflowGuardListenerPassTest extends TestCase $this->compilerPass->process($this->container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - * @expectedExceptionMessage The "security.authentication.trust_resolver" service is needed to be able to use the workflow guard listener. - */ public function testExceptionIfTheAuthenticationTrustResolverServiceIsNotPresent() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); + $this->expectExceptionMessage('The "security.authentication.trust_resolver" service is needed to be able to use the workflow guard listener.'); $this->container->setParameter('workflow.has_guard_listeners', true); $this->container->register('security.token_storage', TokenStorageInterface::class); $this->container->register('security.authorization_checker', AuthorizationCheckerInterface::class); @@ -94,12 +88,10 @@ class WorkflowGuardListenerPassTest extends TestCase $this->compilerPass->process($this->container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - * @expectedExceptionMessage The "security.role_hierarchy" service is needed to be able to use the workflow guard listener. - */ public function testExceptionIfTheRoleHierarchyServiceIsNotPresent() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); + $this->expectExceptionMessage('The "security.role_hierarchy" service is needed to be able to use the workflow guard listener.'); $this->container->setParameter('workflow.has_guard_listeners', true); $this->container->register('security.token_storage', TokenStorageInterface::class); $this->container->register('security.authorization_checker', AuthorizationCheckerInterface::class); diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/ConfigurationTest.php b/lib/symfony/framework-bundle/Tests/DependencyInjection/ConfigurationTest.php index b1dea4cba..e66c9ebfc 100644 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/ConfigurationTest.php +++ b/lib/symfony/framework-bundle/Tests/DependencyInjection/ConfigurationTest.php @@ -104,10 +104,10 @@ class ConfigurationTest extends TestCase /** * @dataProvider getTestInvalidSessionName - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException */ public function testInvalidSessionName($sessionName) { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $processor = new Processor(); $processor->processConfiguration( new Configuration(true), @@ -160,10 +160,10 @@ class ConfigurationTest extends TestCase /** * @group legacy - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException */ public function testInvalidTypeTrustedProxies() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $processor = new Processor(); $configuration = new Configuration(true); $processor->processConfiguration($configuration, [ @@ -176,10 +176,10 @@ class ConfigurationTest extends TestCase /** * @group legacy - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException */ public function testInvalidValueTrustedProxies() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $processor = new Processor(); $configuration = new Configuration(true); @@ -245,12 +245,8 @@ class ConfigurationTest extends TestCase */ public function testInvalidAssetsConfiguration(array $assetConfig, $expectedMessage) { - if (method_exists($this, 'expectException')) { - $this->expectException(InvalidConfigurationException::class); - $this->expectExceptionMessage($expectedMessage); - } else { - $this->setExpectedException(InvalidConfigurationException::class, $expectedMessage); - } + $this->expectException(InvalidConfigurationException::class); + $this->expectExceptionMessage($expectedMessage); $processor = new Processor(); $configuration = new Configuration(true); @@ -296,6 +292,69 @@ class ConfigurationTest extends TestCase yield [$createPackageConfig($config), 'You cannot use both "version" and "json_manifest_path" at the same time under "assets" packages.']; } + /** + * @dataProvider provideValidLockConfigurationTests + */ + public function testValidLockConfiguration($lockConfig, $processedConfig) + { + $processor = new Processor(); + $configuration = new Configuration(true); + $config = $processor->processConfiguration($configuration, [ + [ + 'lock' => $lockConfig, + ], + ]); + + $this->assertArrayHasKey('lock', $config); + + $this->assertEquals($processedConfig, $config['lock']); + } + + public function provideValidLockConfigurationTests() + { + yield [null, ['enabled' => true, 'resources' => ['default' => [class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphore' : 'flock']]]]; + + yield ['flock', ['enabled' => true, 'resources' => ['default' => ['flock']]]]; + yield [['flock', 'semaphore'], ['enabled' => true, 'resources' => ['default' => ['flock', 'semaphore']]]]; + yield [['foo' => 'flock', 'bar' => 'semaphore'], ['enabled' => true, 'resources' => ['foo' => ['flock'], 'bar' => ['semaphore']]]]; + yield [['foo' => ['flock', 'semaphore'], 'bar' => 'semaphore'], ['enabled' => true, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => ['semaphore']]]]; + yield [['default' => 'flock'], ['enabled' => true, 'resources' => ['default' => ['flock']]]]; + + yield [['enabled' => false, 'flock'], ['enabled' => false, 'resources' => ['default' => ['flock']]]]; + yield [['enabled' => false, ['flock', 'semaphore']], ['enabled' => false, 'resources' => ['default' => ['flock', 'semaphore']]]]; + yield [['enabled' => false, 'foo' => 'flock', 'bar' => 'semaphore'], ['enabled' => false, 'resources' => ['foo' => ['flock'], 'bar' => ['semaphore']]]]; + yield [['enabled' => false, 'foo' => ['flock', 'semaphore']], ['enabled' => false, 'resources' => ['foo' => ['flock', 'semaphore']]]]; + yield [['enabled' => false, 'default' => 'flock'], ['enabled' => false, 'resources' => ['default' => ['flock']]]]; + + yield [['resources' => 'flock'], ['enabled' => true, 'resources' => ['default' => ['flock']]]]; + yield [['resources' => ['flock', 'semaphore']], ['enabled' => true, 'resources' => ['default' => ['flock', 'semaphore']]]]; + yield [['resources' => ['foo' => 'flock', 'bar' => 'semaphore']], ['enabled' => true, 'resources' => ['foo' => ['flock'], 'bar' => ['semaphore']]]]; + yield [['resources' => ['foo' => ['flock', 'semaphore'], 'bar' => 'semaphore']], ['enabled' => true, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => ['semaphore']]]]; + yield [['resources' => ['default' => 'flock']], ['enabled' => true, 'resources' => ['default' => ['flock']]]]; + + yield [['enabled' => false, 'resources' => 'flock'], ['enabled' => false, 'resources' => ['default' => ['flock']]]]; + yield [['enabled' => false, 'resources' => ['flock', 'semaphore']], ['enabled' => false, 'resources' => ['default' => ['flock', 'semaphore']]]]; + yield [['enabled' => false, 'resources' => ['foo' => 'flock', 'bar' => 'semaphore']], ['enabled' => false, 'resources' => ['foo' => ['flock'], 'bar' => ['semaphore']]]]; + yield [['enabled' => false, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => 'semaphore']], ['enabled' => false, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => ['semaphore']]]]; + yield [['enabled' => false, 'resources' => ['default' => 'flock']], ['enabled' => false, 'resources' => ['default' => ['flock']]]]; + + // xml + + yield [['resource' => ['flock']], ['enabled' => true, 'resources' => ['default' => ['flock']]]]; + yield [['resource' => ['flock', ['name' => 'foo', 'value' => 'semaphore']]], ['enabled' => true, 'resources' => ['default' => ['flock'], 'foo' => ['semaphore']]]]; + yield [['resource' => [['name' => 'foo', 'value' => 'flock']]], ['enabled' => true, 'resources' => ['foo' => ['flock']]]]; + yield [['resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'foo', 'value' => 'semaphore']]], ['enabled' => true, 'resources' => ['foo' => ['flock', 'semaphore']]]]; + yield [['resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'bar', 'value' => 'semaphore']]], ['enabled' => true, 'resources' => ['foo' => ['flock'], 'bar' => ['semaphore']]]]; + yield [['resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'foo', 'value' => 'semaphore'], ['name' => 'bar', 'value' => 'semaphore']]], ['enabled' => true, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => ['semaphore']]]]; + + yield [['enabled' => false, 'resource' => ['flock']], ['enabled' => false, 'resources' => ['default' => ['flock']]]]; + yield [['enabled' => false, 'resource' => ['flock', ['name' => 'foo', 'value' => 'semaphore']]], ['enabled' => false, 'resources' => ['default' => ['flock'], 'foo' => ['semaphore']]]]; + yield [['enabled' => false, 'resource' => [['name' => 'foo', 'value' => 'flock']]], ['enabled' => false, 'resources' => ['foo' => ['flock']]]]; + yield [['enabled' => false, 'resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'foo', 'value' => 'semaphore']]], ['enabled' => false, 'resources' => ['foo' => ['flock', 'semaphore']]]]; + yield [['enabled' => false, 'resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'bar', 'value' => 'semaphore']]], ['enabled' => false, 'resources' => ['foo' => ['flock'], 'bar' => ['semaphore']]]]; + yield [['enabled' => false, 'resource' => [['name' => 'foo', 'value' => 'flock'], ['name' => 'foo', 'value' => 'semaphore'], ['name' => 'bar', 'value' => 'semaphore']]], ['enabled' => false, 'resources' => ['foo' => ['flock', 'semaphore'], 'bar' => ['semaphore']]]]; + } + protected static function getBundleDefaultConfig() { return [ @@ -378,6 +437,7 @@ class ConfigurationTest extends TestCase 'handler_id' => 'session.handler.native_file', 'cookie_httponly' => true, 'gc_probability' => 1, + 'save_path' => '%kernel.cache_dir%/sessions', 'metadata_update_threshold' => '0', 'use_strict_mode' => true, ], diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/Fixtures/php/session_savepath.php b/lib/symfony/framework-bundle/Tests/DependencyInjection/Fixtures/php/session_savepath.php deleted file mode 100644 index 89841bca4..000000000 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/Fixtures/php/session_savepath.php +++ /dev/null @@ -1,8 +0,0 @@ -loadFromExtension('framework', [ - 'session' => [ - 'handler_id' => null, - 'save_path' => '/some/path', - ], -]); diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/Fixtures/xml/session_savepath.xml b/lib/symfony/framework-bundle/Tests/DependencyInjection/Fixtures/xml/session_savepath.xml deleted file mode 100644 index a9ddd8016..000000000 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/Fixtures/xml/session_savepath.xml +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/Fixtures/yml/session_savepath.yml b/lib/symfony/framework-bundle/Tests/DependencyInjection/Fixtures/yml/session_savepath.yml deleted file mode 100644 index 174ebe586..000000000 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/Fixtures/yml/session_savepath.yml +++ /dev/null @@ -1,4 +0,0 @@ -framework: - session: - handler_id: null - save_path: /some/path diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/FrameworkExtensionTest.php b/lib/symfony/framework-bundle/Tests/DependencyInjection/FrameworkExtensionTest.php index ef074bd16..556fd9afd 100644 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/FrameworkExtensionTest.php +++ b/lib/symfony/framework-bundle/Tests/DependencyInjection/FrameworkExtensionTest.php @@ -85,7 +85,9 @@ abstract class FrameworkExtensionTest extends TestCase $container = $this->createContainerFromFile('property_accessor'); if (!method_exists(PropertyAccessor::class, 'createCache')) { - return $this->assertFalse($container->hasDefinition('cache.property_access')); + $this->assertFalse($container->hasDefinition('cache.property_access')); + + return; } $cache = $container->getDefinition('cache.property_access'); @@ -98,7 +100,9 @@ abstract class FrameworkExtensionTest extends TestCase $container = $this->createContainerFromFile('property_accessor', ['kernel.debug' => true]); if (!method_exists(PropertyAccessor::class, 'createCache')) { - return $this->assertFalse($container->hasDefinition('cache.property_access')); + $this->assertFalse($container->hasDefinition('cache.property_access')); + + return; } $cache = $container->getDefinition('cache.property_access'); @@ -106,12 +110,10 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertSame(ArrayAdapter::class, $cache->getClass(), 'ArrayAdapter should be used in debug mode'); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage CSRF protection needs sessions to be enabled. - */ public function testCsrfProtectionNeedsSessionToBeEnabled() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('CSRF protection needs sessions to be enabled.'); $this->createContainerFromFile('csrf_needs_session'); } @@ -249,42 +251,34 @@ abstract class FrameworkExtensionTest extends TestCase */ public function testDeprecatedWorkflowMissingType() { - $container = $this->createContainerFromFile('workflows_without_type'); + $this->createContainerFromFile('workflows_without_type'); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage "type" and "service" cannot be used together. - */ public function testWorkflowCannotHaveBothTypeAndService() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('"type" and "service" cannot be used together.'); $this->createContainerFromFile('workflow_with_type_and_service'); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage "supports" and "support_strategy" cannot be used together. - */ public function testWorkflowCannotHaveBothSupportsAndSupportStrategy() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('"supports" and "support_strategy" cannot be used together.'); $this->createContainerFromFile('workflow_with_support_and_support_strategy'); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage "supports" or "support_strategy" should be configured. - */ public function testWorkflowShouldHaveOneOfSupportsAndSupportStrategy() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('"supports" or "support_strategy" should be configured.'); $this->createContainerFromFile('workflow_without_support_and_support_strategy'); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - * @expectedExceptionMessage "arguments" and "service" cannot be used together. - */ public function testWorkflowCannotHaveBothArgumentsAndService() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); + $this->expectExceptionMessage('"arguments" and "service" cannot be used together.'); $this->createContainerFromFile('workflow_with_arguments_and_service'); } @@ -430,11 +424,9 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertEquals('xml', $arguments[2]['resource_type'], '->registerRouterConfiguration() sets routing resource type'); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - */ public function testRouterRequiresResourceOption() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $container = $this->createContainer(); $loader = new FrameworkExtension(); $loader->load([['router' => true]], $container); @@ -473,14 +465,6 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertNull($container->getDefinition('session.storage.php_bridge')->getArgument(0)); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - */ - public function testNullSessionHandlerWithSavePath() - { - $this->createContainerFromFile('session_savepath'); - } - public function testRequest() { $container = $this->createContainerFromFile('full'); @@ -645,11 +629,9 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertFalse($container->has('templating.helper.translator')); } - /** - * @expectedException \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException - */ public function testTemplatingRequiresAtLeastOneEngine() { + $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); $container = $this->createContainer(); $loader = new FrameworkExtension(); $loader->load([['templating' => null]], $container); @@ -840,9 +822,9 @@ abstract class FrameworkExtensionTest extends TestCase $this->assertSame('addYamlMappings', $calls[4][0]); $this->assertCount(3, $calls[4][1][0]); - $this->assertContains('foo.yml', $calls[4][1][0][0]); - $this->assertContains('validation.yml', $calls[4][1][0][1]); - $this->assertContains('validation.yaml', $calls[4][1][0][2]); + $this->assertStringContainsString('foo.yml', $calls[4][1][0][0]); + $this->assertStringContainsString('validation.yml', $calls[4][1][0][1]); + $this->assertStringContainsString('validation.yaml', $calls[4][1][0][2]); } public function testFormsCanBeEnabledWithoutCsrfProtection() diff --git a/lib/symfony/framework-bundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php b/lib/symfony/framework-bundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php index ec39372b1..afccc84d5 100644 --- a/lib/symfony/framework-bundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php +++ b/lib/symfony/framework-bundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php @@ -23,11 +23,9 @@ class PhpFrameworkExtensionTest extends FrameworkExtensionTest $loader->load($file.'.php'); } - /** - * @expectedException \LogicException - */ public function testAssetsCannotHavePathAndUrl() { + $this->expectException('LogicException'); $this->createContainerFromClosure(function ($container) { $container->loadFromExtension('framework', [ 'assets' => [ @@ -38,11 +36,9 @@ class PhpFrameworkExtensionTest extends FrameworkExtensionTest }); } - /** - * @expectedException \LogicException - */ public function testAssetPackageCannotHavePathAndUrl() { + $this->expectException('LogicException'); $this->createContainerFromClosure(function ($container) { $container->loadFromExtension('framework', [ 'assets' => [ diff --git a/lib/symfony/framework-bundle/Tests/Functional/Bundle/TestBundle/DependencyInjection/TestExtension.php b/lib/symfony/framework-bundle/Tests/Functional/Bundle/TestBundle/DependencyInjection/TestExtension.php index 59670fdd1..0ae7669ce 100644 --- a/lib/symfony/framework-bundle/Tests/Functional/Bundle/TestBundle/DependencyInjection/TestExtension.php +++ b/lib/symfony/framework-bundle/Tests/Functional/Bundle/TestBundle/DependencyInjection/TestExtension.php @@ -26,7 +26,7 @@ class TestExtension extends Extension implements PrependExtensionInterface public function load(array $configs, ContainerBuilder $container) { $configuration = $this->getConfiguration($configs, $container); - $config = $this->processConfiguration($configuration, $configs); + $this->processConfiguration($configuration, $configs); $container->setAlias('test.annotation_reader', new Alias('annotation_reader', true)); } diff --git a/lib/symfony/framework-bundle/Tests/Functional/CachePoolClearCommandTest.php b/lib/symfony/framework-bundle/Tests/Functional/CachePoolClearCommandTest.php index e30a0e1ee..8a0f6593d 100644 --- a/lib/symfony/framework-bundle/Tests/Functional/CachePoolClearCommandTest.php +++ b/lib/symfony/framework-bundle/Tests/Functional/CachePoolClearCommandTest.php @@ -31,8 +31,8 @@ class CachePoolClearCommandTest extends AbstractWebTestCase $tester->execute(['pools' => ['cache.private_pool']], ['decorated' => false]); $this->assertSame(0, $tester->getStatusCode(), 'cache:pool:clear exits with 0 in case of success'); - $this->assertContains('Clearing cache pool: cache.private_pool', $tester->getDisplay()); - $this->assertContains('[OK] Cache was successfully cleared.', $tester->getDisplay()); + $this->assertStringContainsString('Clearing cache pool: cache.private_pool', $tester->getDisplay()); + $this->assertStringContainsString('[OK] Cache was successfully cleared.', $tester->getDisplay()); } public function testClearPublicPool() @@ -41,8 +41,8 @@ class CachePoolClearCommandTest extends AbstractWebTestCase $tester->execute(['pools' => ['cache.public_pool']], ['decorated' => false]); $this->assertSame(0, $tester->getStatusCode(), 'cache:pool:clear exits with 0 in case of success'); - $this->assertContains('Clearing cache pool: cache.public_pool', $tester->getDisplay()); - $this->assertContains('[OK] Cache was successfully cleared.', $tester->getDisplay()); + $this->assertStringContainsString('Clearing cache pool: cache.public_pool', $tester->getDisplay()); + $this->assertStringContainsString('[OK] Cache was successfully cleared.', $tester->getDisplay()); } public function testClearPoolWithCustomClearer() @@ -51,8 +51,8 @@ class CachePoolClearCommandTest extends AbstractWebTestCase $tester->execute(['pools' => ['cache.pool_with_clearer']], ['decorated' => false]); $this->assertSame(0, $tester->getStatusCode(), 'cache:pool:clear exits with 0 in case of success'); - $this->assertContains('Clearing cache pool: cache.pool_with_clearer', $tester->getDisplay()); - $this->assertContains('[OK] Cache was successfully cleared.', $tester->getDisplay()); + $this->assertStringContainsString('Clearing cache pool: cache.pool_with_clearer', $tester->getDisplay()); + $this->assertStringContainsString('[OK] Cache was successfully cleared.', $tester->getDisplay()); } public function testCallClearer() @@ -61,16 +61,14 @@ class CachePoolClearCommandTest extends AbstractWebTestCase $tester->execute(['pools' => ['cache.app_clearer']], ['decorated' => false]); $this->assertSame(0, $tester->getStatusCode(), 'cache:pool:clear exits with 0 in case of success'); - $this->assertContains('Calling cache clearer: cache.app_clearer', $tester->getDisplay()); - $this->assertContains('[OK] Cache was successfully cleared.', $tester->getDisplay()); + $this->assertStringContainsString('Calling cache clearer: cache.app_clearer', $tester->getDisplay()); + $this->assertStringContainsString('[OK] Cache was successfully cleared.', $tester->getDisplay()); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException - * @expectedExceptionMessage You have requested a non-existent service "unknown_pool" - */ public function testClearUnexistingPool() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'); + $this->expectExceptionMessage('You have requested a non-existent service "unknown_pool"'); $this->createCommandTester() ->execute(['pools' => ['unknown_pool']], ['decorated' => false]); } @@ -88,7 +86,7 @@ class CachePoolClearCommandTest extends AbstractWebTestCase $tester->execute(['pools' => []]); - $this->assertContains('Cache was successfully cleared', $tester->getDisplay()); + $this->assertStringContainsString('Cache was successfully cleared', $tester->getDisplay()); } private function createCommandTester() diff --git a/lib/symfony/framework-bundle/Tests/Functional/CachePoolsTest.php b/lib/symfony/framework-bundle/Tests/Functional/CachePoolsTest.php index ebf6561a6..13815b959 100644 --- a/lib/symfony/framework-bundle/Tests/Functional/CachePoolsTest.php +++ b/lib/symfony/framework-bundle/Tests/Functional/CachePoolsTest.php @@ -34,7 +34,7 @@ class CachePoolsTest extends AbstractWebTestCase throw $e; } $this->markTestSkipped($e->getMessage()); - } catch (\PHPUnit_Framework_Error_Warning $e) { + } catch (\PHPUnit\Framework\Error\Warning $e) { if (0 !== strpos($e->getMessage(), 'unable to connect to')) { throw $e; } @@ -59,7 +59,7 @@ class CachePoolsTest extends AbstractWebTestCase throw $e; } $this->markTestSkipped($e->getMessage()); - } catch (\PHPUnit_Framework_Error_Warning $e) { + } catch (\PHPUnit\Framework\Error\Warning $e) { if (0 !== strpos($e->getMessage(), 'unable to connect to')) { throw $e; } diff --git a/lib/symfony/framework-bundle/Tests/Functional/ConfigDebugCommandTest.php b/lib/symfony/framework-bundle/Tests/Functional/ConfigDebugCommandTest.php index c10750eaa..a2e88f003 100644 --- a/lib/symfony/framework-bundle/Tests/Functional/ConfigDebugCommandTest.php +++ b/lib/symfony/framework-bundle/Tests/Functional/ConfigDebugCommandTest.php @@ -36,7 +36,7 @@ class ConfigDebugCommandTest extends AbstractWebTestCase $ret = $tester->execute(['name' => 'TestBundle']); $this->assertSame(0, $ret, 'Returns 0 in case of success'); - $this->assertContains('custom: foo', $tester->getDisplay()); + $this->assertStringContainsString('custom: foo', $tester->getDisplay()); } public function testDumpBundleOption() @@ -45,7 +45,7 @@ class ConfigDebugCommandTest extends AbstractWebTestCase $ret = $tester->execute(['name' => 'TestBundle', 'path' => 'custom']); $this->assertSame(0, $ret, 'Returns 0 in case of success'); - $this->assertContains('foo', $tester->getDisplay()); + $this->assertStringContainsString('foo', $tester->getDisplay()); } public function testParametersValuesAreResolved() @@ -54,8 +54,8 @@ class ConfigDebugCommandTest extends AbstractWebTestCase $ret = $tester->execute(['name' => 'framework']); $this->assertSame(0, $ret, 'Returns 0 in case of success'); - $this->assertContains("locale: '%env(LOCALE)%'", $tester->getDisplay()); - $this->assertContains('secret: test', $tester->getDisplay()); + $this->assertStringContainsString("locale: '%env(LOCALE)%'", $tester->getDisplay()); + $this->assertStringContainsString('secret: test', $tester->getDisplay()); } public function testDumpUndefinedBundleOption() @@ -63,7 +63,7 @@ class ConfigDebugCommandTest extends AbstractWebTestCase $tester = $this->createCommandTester(); $tester->execute(['name' => 'TestBundle', 'path' => 'foo']); - $this->assertContains('Unable to find configuration for "test.foo"', $tester->getDisplay()); + $this->assertStringContainsString('Unable to find configuration for "test.foo"', $tester->getDisplay()); } /** diff --git a/lib/symfony/framework-bundle/Tests/Functional/ConfigDumpReferenceCommandTest.php b/lib/symfony/framework-bundle/Tests/Functional/ConfigDumpReferenceCommandTest.php index b8ac6645f..aa5dba65c 100644 --- a/lib/symfony/framework-bundle/Tests/Functional/ConfigDumpReferenceCommandTest.php +++ b/lib/symfony/framework-bundle/Tests/Functional/ConfigDumpReferenceCommandTest.php @@ -36,8 +36,8 @@ class ConfigDumpReferenceCommandTest extends AbstractWebTestCase $ret = $tester->execute(['name' => 'TestBundle']); $this->assertSame(0, $ret, 'Returns 0 in case of success'); - $this->assertContains('test:', $tester->getDisplay()); - $this->assertContains(' custom:', $tester->getDisplay()); + $this->assertStringContainsString('test:', $tester->getDisplay()); + $this->assertStringContainsString(' custom:', $tester->getDisplay()); } public function testDumpAtPath() @@ -70,7 +70,7 @@ EOL ]); $this->assertSame(1, $ret); - $this->assertContains('[ERROR] The "path" option is only available for the "yaml" format.', $tester->getDisplay()); + $this->assertStringContainsString('[ERROR] The "path" option is only available for the "yaml" format.', $tester->getDisplay()); } /** diff --git a/lib/symfony/framework-bundle/Tests/Functional/ContainerDebugCommandTest.php b/lib/symfony/framework-bundle/Tests/Functional/ContainerDebugCommandTest.php index 21f33df0c..6f936c796 100644 --- a/lib/symfony/framework-bundle/Tests/Functional/ContainerDebugCommandTest.php +++ b/lib/symfony/framework-bundle/Tests/Functional/ContainerDebugCommandTest.php @@ -44,7 +44,7 @@ class ContainerDebugCommandTest extends AbstractWebTestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'debug:container']); - $this->assertContains('public', $tester->getDisplay()); + $this->assertStringContainsString('public', $tester->getDisplay()); } public function testPrivateAlias() @@ -56,11 +56,11 @@ class ContainerDebugCommandTest extends AbstractWebTestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'debug:container', '--show-private' => true]); - $this->assertContains('public', $tester->getDisplay()); - $this->assertContains('private_alias', $tester->getDisplay()); + $this->assertStringContainsString('public', $tester->getDisplay()); + $this->assertStringContainsString('private_alias', $tester->getDisplay()); $tester->run(['command' => 'debug:container']); - $this->assertContains('public', $tester->getDisplay()); - $this->assertNotContains('private_alias', $tester->getDisplay()); + $this->assertStringContainsString('public', $tester->getDisplay()); + $this->assertStringNotContainsString('private_alias', $tester->getDisplay()); } } diff --git a/lib/symfony/framework-bundle/Tests/Functional/DebugAutowiringCommandTest.php b/lib/symfony/framework-bundle/Tests/Functional/DebugAutowiringCommandTest.php index 8e55eb5d8..6d163b783 100644 --- a/lib/symfony/framework-bundle/Tests/Functional/DebugAutowiringCommandTest.php +++ b/lib/symfony/framework-bundle/Tests/Functional/DebugAutowiringCommandTest.php @@ -29,8 +29,8 @@ class DebugAutowiringCommandTest extends AbstractWebTestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'debug:autowiring']); - $this->assertContains('Symfony\Component\HttpKernel\HttpKernelInterface', $tester->getDisplay()); - $this->assertContains('alias to http_kernel', $tester->getDisplay()); + $this->assertStringContainsString('Symfony\Component\HttpKernel\HttpKernelInterface', $tester->getDisplay()); + $this->assertStringContainsString('alias to http_kernel', $tester->getDisplay()); } public function testSearchArgument() @@ -43,8 +43,8 @@ class DebugAutowiringCommandTest extends AbstractWebTestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'debug:autowiring', 'search' => 'kern']); - $this->assertContains('Symfony\Component\HttpKernel\HttpKernelInterface', $tester->getDisplay()); - $this->assertNotContains('Symfony\Component\Routing\RouterInterface', $tester->getDisplay()); + $this->assertStringContainsString('Symfony\Component\HttpKernel\HttpKernelInterface', $tester->getDisplay()); + $this->assertStringNotContainsString('Symfony\Component\Routing\RouterInterface', $tester->getDisplay()); } public function testSearchNoResults() @@ -57,7 +57,7 @@ class DebugAutowiringCommandTest extends AbstractWebTestCase $tester = new ApplicationTester($application); $tester->run(['command' => 'debug:autowiring', 'search' => 'foo_fake'], ['capture_stderr_separately' => true]); - $this->assertContains('No autowirable classes or interfaces found matching "foo_fake"', $tester->getErrorOutput()); + $this->assertStringContainsString('No autowirable classes or interfaces found matching "foo_fake"', $tester->getErrorOutput()); $this->assertEquals(1, $tester->getStatusCode()); } } diff --git a/lib/symfony/framework-bundle/Tests/Functional/ProfilerTest.php b/lib/symfony/framework-bundle/Tests/Functional/ProfilerTest.php index ec3c47e76..35c2e63b7 100644 --- a/lib/symfony/framework-bundle/Tests/Functional/ProfilerTest.php +++ b/lib/symfony/framework-bundle/Tests/Functional/ProfilerTest.php @@ -24,16 +24,16 @@ class ProfilerTest extends AbstractWebTestCase } $client->request('GET', '/profiler'); - $this->assertFalse($client->getProfile()); + $this->assertNull($client->getProfile()); // enable the profiler for the next request $client->enableProfiler(); - $this->assertFalse($client->getProfile()); + $this->assertNull($client->getProfile()); $client->request('GET', '/profiler'); - $this->assertInternalType('object', $client->getProfile()); + $this->assertIsObject($client->getProfile()); $client->request('GET', '/profiler'); - $this->assertFalse($client->getProfile()); + $this->assertNull($client->getProfile()); } public function getConfigs() diff --git a/lib/symfony/framework-bundle/Tests/Functional/SessionTest.php b/lib/symfony/framework-bundle/Tests/Functional/SessionTest.php index 0fa8a09b4..3a87f7e4e 100644 --- a/lib/symfony/framework-bundle/Tests/Functional/SessionTest.php +++ b/lib/symfony/framework-bundle/Tests/Functional/SessionTest.php @@ -27,23 +27,23 @@ class SessionTest extends AbstractWebTestCase // no session $crawler = $client->request('GET', '/session'); - $this->assertContains('You are new here and gave no name.', $crawler->text()); + $this->assertStringContainsString('You are new here and gave no name.', $crawler->text()); // remember name $crawler = $client->request('GET', '/session/drak'); - $this->assertContains('Hello drak, nice to meet you.', $crawler->text()); + $this->assertStringContainsString('Hello drak, nice to meet you.', $crawler->text()); // prove remembered name $crawler = $client->request('GET', '/session'); - $this->assertContains('Welcome back drak, nice to meet you.', $crawler->text()); + $this->assertStringContainsString('Welcome back drak, nice to meet you.', $crawler->text()); // clear session $crawler = $client->request('GET', '/session_logout'); - $this->assertContains('Session cleared.', $crawler->text()); + $this->assertStringContainsString('Session cleared.', $crawler->text()); // prove cleared session $crawler = $client->request('GET', '/session'); - $this->assertContains('You are new here and gave no name.', $crawler->text()); + $this->assertStringContainsString('You are new here and gave no name.', $crawler->text()); } /** @@ -59,14 +59,14 @@ class SessionTest extends AbstractWebTestCase } // set flash - $crawler = $client->request('GET', '/session_setflash/Hello%20world.'); + $client->request('GET', '/session_setflash/Hello%20world.'); // check flash displays on redirect - $this->assertContains('Hello world.', $client->followRedirect()->text()); + $this->assertStringContainsString('Hello world.', $client->followRedirect()->text()); // check flash is gone $crawler = $client->request('GET', '/session_showflash'); - $this->assertContains('No flash was set.', $crawler->text()); + $this->assertStringContainsString('No flash was set.', $crawler->text()); } /** @@ -91,39 +91,39 @@ class SessionTest extends AbstractWebTestCase // new session, so no name set. $crawler1 = $client1->request('GET', '/session'); - $this->assertContains('You are new here and gave no name.', $crawler1->text()); + $this->assertStringContainsString('You are new here and gave no name.', $crawler1->text()); // set name of client1 $crawler1 = $client1->request('GET', '/session/client1'); - $this->assertContains('Hello client1, nice to meet you.', $crawler1->text()); + $this->assertStringContainsString('Hello client1, nice to meet you.', $crawler1->text()); // no session for client2 $crawler2 = $client2->request('GET', '/session'); - $this->assertContains('You are new here and gave no name.', $crawler2->text()); + $this->assertStringContainsString('You are new here and gave no name.', $crawler2->text()); // remember name client2 $crawler2 = $client2->request('GET', '/session/client2'); - $this->assertContains('Hello client2, nice to meet you.', $crawler2->text()); + $this->assertStringContainsString('Hello client2, nice to meet you.', $crawler2->text()); // prove remembered name of client1 $crawler1 = $client1->request('GET', '/session'); - $this->assertContains('Welcome back client1, nice to meet you.', $crawler1->text()); + $this->assertStringContainsString('Welcome back client1, nice to meet you.', $crawler1->text()); // prove remembered name of client2 $crawler2 = $client2->request('GET', '/session'); - $this->assertContains('Welcome back client2, nice to meet you.', $crawler2->text()); + $this->assertStringContainsString('Welcome back client2, nice to meet you.', $crawler2->text()); // clear client1 $crawler1 = $client1->request('GET', '/session_logout'); - $this->assertContains('Session cleared.', $crawler1->text()); + $this->assertStringContainsString('Session cleared.', $crawler1->text()); // prove client1 data is cleared $crawler1 = $client1->request('GET', '/session'); - $this->assertContains('You are new here and gave no name.', $crawler1->text()); + $this->assertStringContainsString('You are new here and gave no name.', $crawler1->text()); // prove remembered name of client2 remains untouched. $crawler2 = $client2->request('GET', '/session'); - $this->assertContains('Welcome back client2, nice to meet you.', $crawler2->text()); + $this->assertStringContainsString('Welcome back client2, nice to meet you.', $crawler2->text()); } /** diff --git a/lib/symfony/framework-bundle/Tests/Routing/RouterTest.php b/lib/symfony/framework-bundle/Tests/Routing/RouterTest.php index 9fe45527c..414eed17d 100644 --- a/lib/symfony/framework-bundle/Tests/Routing/RouterTest.php +++ b/lib/symfony/framework-bundle/Tests/Routing/RouterTest.php @@ -14,6 +14,7 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Routing; use PHPUnit\Framework\TestCase; use Symfony\Bundle\FrameworkBundle\Routing\Router; use Symfony\Component\DependencyInjection\Config\ContainerParametersResource; +use Symfony\Component\DependencyInjection\Exception\RuntimeException; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; @@ -122,23 +123,21 @@ class RouterTest extends TestCase $routes->add('foo', new Route('/before/%parameter.foo%/after/%%escaped%%')); $sc = $this->getServiceContainer($routes); - $sc->setParameter('parameter.foo', 'foo'); + $sc->setParameter('parameter.foo', 'foo-%%escaped%%'); $router = new Router($sc, 'foo'); $route = $router->getRouteCollection()->get('foo'); $this->assertEquals( - '/before/foo/after/%escaped%', + '/before/foo-%escaped%/after/%escaped%', $route->getPath() ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Using "%env(FOO)%" is not allowed in routing configuration. - */ public function testEnvPlaceholders() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Using "%env(FOO)%" is not allowed in routing configuration.'); $routes = new RouteCollection(); $routes->add('foo', new Route('/%env(FOO)%')); @@ -147,6 +146,22 @@ class RouterTest extends TestCase $router->getRouteCollection(); } + public function testIndirectEnvPlaceholders() + { + $routes = new RouteCollection(); + + $routes->add('foo', new Route('/%foo%')); + + $router = new Router($container = $this->getServiceContainer($routes), 'foo'); + $container->setParameter('foo', 'foo-%bar%'); + $container->setParameter('bar', '%env(string:FOO)%'); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Using "%env(string:FOO)%" is not allowed in routing configuration.'); + + $router->getRouteCollection(); + } + public function testHostPlaceholders() { $routes = new RouteCollection(); @@ -168,12 +183,10 @@ class RouterTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException - * @expectedExceptionMessage You have requested a non-existent parameter "nope". - */ public function testExceptionOnNonExistentParameter() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException'); + $this->expectExceptionMessage('You have requested a non-existent parameter "nope".'); $routes = new RouteCollection(); $routes->add('foo', new Route('/%nope%')); @@ -184,12 +197,10 @@ class RouterTest extends TestCase $router->getRouteCollection()->get('foo'); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage The container parameter "object", used in the route configuration value "/%object%", must be a string or numeric, but it is of type object. - */ public function testExceptionOnNonStringParameter() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('The container parameter "object", used in the route configuration value "/%object%", must be a string or numeric, but it is of type object.'); $routes = new RouteCollection(); $routes->add('foo', new Route('/%object%')); diff --git a/lib/symfony/framework-bundle/Tests/Templating/DelegatingEngineTest.php b/lib/symfony/framework-bundle/Tests/Templating/DelegatingEngineTest.php index 1fae0526d..547339559 100644 --- a/lib/symfony/framework-bundle/Tests/Templating/DelegatingEngineTest.php +++ b/lib/symfony/framework-bundle/Tests/Templating/DelegatingEngineTest.php @@ -43,12 +43,10 @@ class DelegatingEngineTest extends TestCase $this->assertSame($secondEngine, $delegatingEngine->getEngine('template.php')); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage No engine is able to work with the template "template.php" - */ public function testGetInvalidEngine() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('No engine is able to work with the template "template.php"'); $firstEngine = $this->getEngineMock('template.php', false); $secondEngine = $this->getEngineMock('template.php', false); $container = $this->getContainerMock([ diff --git a/lib/symfony/framework-bundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php b/lib/symfony/framework-bundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php index 03b2ed696..3ac441562 100644 --- a/lib/symfony/framework-bundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php +++ b/lib/symfony/framework-bundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php @@ -52,11 +52,12 @@ class FormHelperDivLayoutTest extends AbstractDivLayoutTest ]); } - protected function tearDown() + /** + * @after + */ + public function doTearDown() { $this->engine = null; - - parent::tearDown(); } public function testStartTagHasNoActionAttributeWhenActionIsEmpty() diff --git a/lib/symfony/framework-bundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php b/lib/symfony/framework-bundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php index bd088078c..e7555b234 100644 --- a/lib/symfony/framework-bundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php +++ b/lib/symfony/framework-bundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php @@ -77,11 +77,12 @@ class FormHelperTableLayoutTest extends AbstractTableLayoutTest ]); } - protected function tearDown() + /** + * @after + */ + public function doTearDown() { $this->engine = null; - - parent::tearDown(); } protected function renderForm(FormView $view, array $vars = []) diff --git a/lib/symfony/framework-bundle/Tests/Templating/Loader/TemplateLocatorTest.php b/lib/symfony/framework-bundle/Tests/Templating/Loader/TemplateLocatorTest.php index c78b7e5b2..b19ce0d27 100644 --- a/lib/symfony/framework-bundle/Tests/Templating/Loader/TemplateLocatorTest.php +++ b/lib/symfony/framework-bundle/Tests/Templating/Loader/TemplateLocatorTest.php @@ -69,7 +69,7 @@ class TemplateLocatorTest extends TestCase $locator->locate($template); $this->fail('->locate() should throw an exception when the file is not found.'); } catch (\InvalidArgumentException $e) { - $this->assertContains( + $this->assertStringContainsString( $errorMessage, $e->getMessage(), 'TemplateLocator exception should propagate the FileLocator exception message' @@ -77,11 +77,9 @@ class TemplateLocatorTest extends TestCase } } - /** - * @expectedException \InvalidArgumentException - */ public function testThrowsAnExceptionWhenTemplateIsNotATemplateReferenceInterface() { + $this->expectException('InvalidArgumentException'); $locator = new TemplateLocator($this->getFileLocator()); $locator->locate('template'); } diff --git a/lib/symfony/framework-bundle/Tests/Templating/PhpEngineTest.php b/lib/symfony/framework-bundle/Tests/Templating/PhpEngineTest.php index 9628828af..16c668117 100644 --- a/lib/symfony/framework-bundle/Tests/Templating/PhpEngineTest.php +++ b/lib/symfony/framework-bundle/Tests/Templating/PhpEngineTest.php @@ -43,11 +43,9 @@ class PhpEngineTest extends TestCase $this->assertEmpty($globals['app']->getRequest()); } - /** - * @expectedException \InvalidArgumentException - */ public function testGetInvalidHelper() { + $this->expectException('InvalidArgumentException'); $container = $this->getContainer(); $loader = $this->getMockForAbstractClass('Symfony\Component\Templating\Loader\Loader'); $engine = new PhpEngine(new TemplateNameParser(), $container, $loader); diff --git a/lib/symfony/framework-bundle/Tests/Templating/TemplateNameParserTest.php b/lib/symfony/framework-bundle/Tests/Templating/TemplateNameParserTest.php index 4460d2ac2..b9cb30859 100644 --- a/lib/symfony/framework-bundle/Tests/Templating/TemplateNameParserTest.php +++ b/lib/symfony/framework-bundle/Tests/Templating/TemplateNameParserTest.php @@ -74,11 +74,9 @@ class TemplateNameParserTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - */ public function testParseValidNameWithNotFoundBundle() { + $this->expectException('InvalidArgumentException'); $this->parser->parse('BarBundle:Post:index.html.php'); } diff --git a/lib/symfony/framework-bundle/Tests/Translation/TranslatorTest.php b/lib/symfony/framework-bundle/Tests/Translation/TranslatorTest.php index 9dfd861db..e38e11601 100644 --- a/lib/symfony/framework-bundle/Tests/Translation/TranslatorTest.php +++ b/lib/symfony/framework-bundle/Tests/Translation/TranslatorTest.php @@ -107,10 +107,10 @@ class TranslatorTest extends TestCase /** * @group legacy * @expectedDeprecation The "Symfony\Bundle\FrameworkBundle\Translation\Translator::__construct()" method takes the default locale as the 3rd argument since Symfony 3.3. Not passing it is deprecated and will trigger an error in 4.0. - * @expectedException \InvalidArgumentException */ public function testTransWithCachingWithInvalidLocaleOmittingLocale() { + $this->expectException('InvalidArgumentException'); $loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock(); $translator = $this->getTranslator($loader, ['cache_dir' => $this->tmpDir], 'loader', '\Symfony\Bundle\FrameworkBundle\Tests\Translation\TranslatorWithInvalidLocale', null); @@ -156,13 +156,13 @@ class TranslatorTest extends TestCase /** * @group legacy - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Missing third $defaultLocale argument. */ public function testGetDefaultLocaleOmittingLocaleWithPsrContainer() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Missing third $defaultLocale argument.'); $container = $this->getMockBuilder(ContainerInterface::class)->getMock(); - $translator = new Translator($container, new MessageFormatter()); + new Translator($container, new MessageFormatter()); } /** @@ -247,12 +247,10 @@ class TranslatorTest extends TestCase $this->assertEquals('foobarbax (sr@latin)', $translator->trans('foobarbax')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Invalid "invalid locale" locale. - */ public function testTransWithCachingWithInvalidLocale() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Invalid "invalid locale" locale.'); $loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock(); $translator = $this->getTranslator($loader, ['cache_dir' => $this->tmpDir], 'loader', '\Symfony\Bundle\FrameworkBundle\Tests\Translation\TranslatorWithInvalidLocale'); @@ -282,12 +280,10 @@ class TranslatorTest extends TestCase $this->assertSame('en', $translator->getLocale()); } - /** - * @expectedException \Symfony\Component\Translation\Exception\InvalidArgumentException - * @expectedExceptionMessage The Translator does not support the following options: 'foo' - */ public function testInvalidOptions() { + $this->expectException('Symfony\Component\Translation\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('The Translator does not support the following options: \'foo\''); $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); (new Translator($container, new MessageFormatter(), 'en', [], ['foo' => 'bar'])); diff --git a/lib/symfony/framework-bundle/Tests/Validator/ConstraintValidatorFactoryTest.php b/lib/symfony/framework-bundle/Tests/Validator/ConstraintValidatorFactoryTest.php index 8afe604c3..1b5409805 100644 --- a/lib/symfony/framework-bundle/Tests/Validator/ConstraintValidatorFactoryTest.php +++ b/lib/symfony/framework-bundle/Tests/Validator/ConstraintValidatorFactoryTest.php @@ -59,11 +59,9 @@ class ConstraintValidatorFactoryTest extends TestCase $this->assertSame($validator, $factory->getInstance(new ConstraintAliasStub())); } - /** - * @expectedException \Symfony\Component\Validator\Exception\ValidatorException - */ public function testGetInstanceInvalidValidatorClass() { + $this->expectException('Symfony\Component\Validator\Exception\ValidatorException'); $constraint = $this->getMockBuilder('Symfony\\Component\\Validator\\Constraint')->getMock(); $constraint ->expects($this->exactly(2)) diff --git a/lib/symfony/framework-bundle/composer.json b/lib/symfony/framework-bundle/composer.json index 40cff711a..dae941c1f 100644 --- a/lib/symfony/framework-bundle/composer.json +++ b/lib/symfony/framework-bundle/composer.json @@ -18,14 +18,14 @@ "require": { "php": "^5.5.9|>=7.0.8", "ext-xml": "*", - "symfony/cache": "~3.4|~4.0", + "symfony/cache": "~3.4.31|^4.3.4", "symfony/class-loader": "~3.2", "symfony/dependency-injection": "^3.4.24|^4.2.5", - "symfony/config": "~3.4|~4.0", + "symfony/config": "^3.4.31|^4.3.4", "symfony/debug": "~2.8|~3.0|~4.0", "symfony/event-dispatcher": "~3.4|~4.0", - "symfony/http-foundation": "^3.3.11|~4.0", - "symfony/http-kernel": "~3.4|~4.0", + "symfony/http-foundation": "^3.4.13|~4.3", + "symfony/http-kernel": "^3.4.31|^4.3.4", "symfony/polyfill-mbstring": "~1.0", "symfony/filesystem": "~2.8|~3.0|~4.0", "symfony/finder": "~2.8|~3.0|~4.0", @@ -36,11 +36,11 @@ "fig/link-util": "^1.0", "symfony/asset": "~3.3|~4.0", "symfony/browser-kit": "~2.8|~3.0|~4.0", - "symfony/console": "~3.4|~4.0", + "symfony/console": "~3.4.31|^4.3.4", "symfony/css-selector": "~2.8|~3.0|~4.0", "symfony/dom-crawler": "~2.8|~3.0|~4.0", "symfony/polyfill-intl-icu": "~1.0", - "symfony/form": "^3.4.22|~4.1.11|^4.2.3", + "symfony/form": "^3.4.31|^4.3.4", "symfony/expression-language": "~2.8|~3.0|~4.0", "symfony/process": "~2.8|~3.0|~4.0", "symfony/security-core": "~3.2|~4.0", @@ -56,7 +56,7 @@ "symfony/property-info": "~3.3|~4.0", "symfony/lock": "~3.4|~4.0", "symfony/web-link": "~3.3|~4.0", - "doctrine/annotations": "~1.0", + "doctrine/annotations": "~1.7", "phpdocumentor/reflection-docblock": "^3.0|^4.0", "twig/twig": "~1.34|~2.4" }, diff --git a/lib/symfony/http-foundation/AcceptHeaderItem.php b/lib/symfony/http-foundation/AcceptHeaderItem.php index f6e896874..96bb0c443 100644 --- a/lib/symfony/http-foundation/AcceptHeaderItem.php +++ b/lib/symfony/http-foundation/AcceptHeaderItem.php @@ -25,7 +25,6 @@ class AcceptHeaderItem /** * @param string $value - * @param array $attributes */ public function __construct($value, array $attributes = []) { diff --git a/lib/symfony/http-foundation/BinaryFileResponse.php b/lib/symfony/http-foundation/BinaryFileResponse.php index 6c9a995e9..f43114111 100644 --- a/lib/symfony/http-foundation/BinaryFileResponse.php +++ b/lib/symfony/http-foundation/BinaryFileResponse.php @@ -327,12 +327,12 @@ class BinaryFileResponse extends Response if (null !== $content) { throw new \LogicException('The content cannot be set on a BinaryFileResponse instance.'); } + + return $this; } /** * {@inheritdoc} - * - * @return false */ public function getContent() { diff --git a/lib/symfony/http-foundation/CHANGELOG.md b/lib/symfony/http-foundation/CHANGELOG.md index 7bfde80ff..c0d890167 100644 --- a/lib/symfony/http-foundation/CHANGELOG.md +++ b/lib/symfony/http-foundation/CHANGELOG.md @@ -21,7 +21,7 @@ CHANGELOG ----- * the `Request::setTrustedProxies()` method takes a new `$trustedHeaderSet` argument, - see http://symfony.com/doc/current/components/http_foundation/trusting_proxies.html for more info, + see https://symfony.com/doc/current/deployment/proxies.html for more info, * deprecated the `Request::setTrustedHeaderName()` and `Request::getTrustedHeaderName()` methods, * added `File\Stream`, to be passed to `BinaryFileResponse` when the size of the served file is unknown, disabling `Range` and `Content-Length` handling, switching to chunked encoding instead diff --git a/lib/symfony/http-foundation/Cookie.php b/lib/symfony/http-foundation/Cookie.php index 83a97087f..98a5ef00a 100644 --- a/lib/symfony/http-foundation/Cookie.php +++ b/lib/symfony/http-foundation/Cookie.php @@ -18,6 +18,10 @@ namespace Symfony\Component\HttpFoundation; */ class Cookie { + const SAMESITE_NONE = 'none'; + const SAMESITE_LAX = 'lax'; + const SAMESITE_STRICT = 'strict'; + protected $name; protected $value; protected $domain; @@ -25,12 +29,13 @@ class Cookie protected $path; protected $secure; protected $httpOnly; + private $raw; private $sameSite; - const SAMESITE_NONE = 'none'; - const SAMESITE_LAX = 'lax'; - const SAMESITE_STRICT = 'strict'; + private static $reservedCharsList = "=,; \t\r\n\v\f"; + private static $reservedCharsFrom = ['=', ',', ';', ' ', "\t", "\r", "\n", "\v", "\f"]; + private static $reservedCharsTo = ['%3D', '%2C', '%3B', '%20', '%09', '%0D', '%0A', '%0B', '%0C']; /** * Creates cookie from raw header string. @@ -97,7 +102,7 @@ class Cookie public function __construct($name, $value = null, $expire = 0, $path = '/', $domain = null, $secure = false, $httpOnly = true, $raw = false, $sameSite = null) { // from PHP source code - if (preg_match("/[=,; \t\r\n\013\014]/", $name)) { + if ($raw && false !== strpbrk($name, self::$reservedCharsList)) { throw new \InvalidArgumentException(sprintf('The cookie name "%s" contains invalid characters.', $name)); } @@ -143,7 +148,13 @@ class Cookie */ public function __toString() { - $str = ($this->isRaw() ? $this->getName() : urlencode($this->getName())).'='; + if ($this->isRaw()) { + $str = $this->getName(); + } else { + $str = str_replace(self::$reservedCharsFrom, self::$reservedCharsTo, $this->getName()); + } + + $str .= '='; if ('' === (string) $this->getValue()) { $str .= 'deleted; expires='.gmdate('D, d-M-Y H:i:s T', time() - 31536001).'; Max-Age=0'; diff --git a/lib/symfony/http-foundation/File/MimeType/ExtensionGuesser.php b/lib/symfony/http-foundation/File/MimeType/ExtensionGuesser.php index 80f4d47f7..f9393df90 100644 --- a/lib/symfony/http-foundation/File/MimeType/ExtensionGuesser.php +++ b/lib/symfony/http-foundation/File/MimeType/ExtensionGuesser.php @@ -90,5 +90,7 @@ class ExtensionGuesser implements ExtensionGuesserInterface return $extension; } } + + return null; } } diff --git a/lib/symfony/http-foundation/File/MimeType/FileBinaryMimeTypeGuesser.php b/lib/symfony/http-foundation/File/MimeType/FileBinaryMimeTypeGuesser.php index 34e015ee5..7045e94df 100644 --- a/lib/symfony/http-foundation/File/MimeType/FileBinaryMimeTypeGuesser.php +++ b/lib/symfony/http-foundation/File/MimeType/FileBinaryMimeTypeGuesser.php @@ -31,7 +31,7 @@ class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface * * @param string $cmd The command to run to get the mime type of a file */ - public function __construct($cmd = 'file -b --mime %s 2>/dev/null') + public function __construct($cmd = 'file -b --mime -- %s 2>/dev/null') { $this->cmd = $cmd; } @@ -74,24 +74,24 @@ class FileBinaryMimeTypeGuesser implements MimeTypeGuesserInterface } if (!self::isSupported()) { - return; + return null; } ob_start(); // need to use --mime instead of -i. see #6641 - passthru(sprintf($this->cmd, escapeshellarg($path)), $return); + passthru(sprintf($this->cmd, escapeshellarg((0 === strpos($path, '-') ? './' : '').$path)), $return); if ($return > 0) { ob_end_clean(); - return; + return null; } $type = trim(ob_get_clean()); - if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) { + if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\+\.]+)#i', $type, $match)) { // it's not a type, but an error message - return; + return null; } return $match[1]; diff --git a/lib/symfony/http-foundation/File/MimeType/FileinfoMimeTypeGuesser.php b/lib/symfony/http-foundation/File/MimeType/FileinfoMimeTypeGuesser.php index bf1ee9f5d..fc4bc4502 100644 --- a/lib/symfony/http-foundation/File/MimeType/FileinfoMimeTypeGuesser.php +++ b/lib/symfony/http-foundation/File/MimeType/FileinfoMimeTypeGuesser.php @@ -26,7 +26,7 @@ class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface /** * @param string $magicFile A magic file to use with the finfo instance * - * @see http://www.php.net/manual/en/function.finfo-open.php + * @see https://php.net/finfo-open */ public function __construct($magicFile = null) { @@ -57,11 +57,11 @@ class FileinfoMimeTypeGuesser implements MimeTypeGuesserInterface } if (!self::isSupported()) { - return; + return null; } if (!$finfo = new \finfo(FILEINFO_MIME_TYPE, $this->magicFile)) { - return; + return null; } return $finfo->file($path); diff --git a/lib/symfony/http-foundation/File/MimeType/MimeTypeGuesser.php b/lib/symfony/http-foundation/File/MimeType/MimeTypeGuesser.php index 95d1ee267..e05269fc8 100644 --- a/lib/symfony/http-foundation/File/MimeType/MimeTypeGuesser.php +++ b/lib/symfony/http-foundation/File/MimeType/MimeTypeGuesser.php @@ -129,5 +129,7 @@ class MimeTypeGuesser implements MimeTypeGuesserInterface if (2 === \count($this->guessers) && !FileBinaryMimeTypeGuesser::isSupported() && !FileinfoMimeTypeGuesser::isSupported()) { throw new \LogicException('Unable to guess the mime type as no guessers are available (Did you enable the php_fileinfo extension?)'); } + + return null; } } diff --git a/lib/symfony/http-foundation/File/MimeType/MimeTypeGuesserInterface.php b/lib/symfony/http-foundation/File/MimeType/MimeTypeGuesserInterface.php index 5ac1acb82..e46e78eef 100644 --- a/lib/symfony/http-foundation/File/MimeType/MimeTypeGuesserInterface.php +++ b/lib/symfony/http-foundation/File/MimeType/MimeTypeGuesserInterface.php @@ -26,7 +26,7 @@ interface MimeTypeGuesserInterface * * @param string $path The path to the file * - * @return string The mime type or NULL, if none could be guessed + * @return string|null The mime type or NULL, if none could be guessed * * @throws FileNotFoundException If the file does not exist * @throws AccessDeniedException If the file could not be read diff --git a/lib/symfony/http-foundation/File/UploadedFile.php b/lib/symfony/http-foundation/File/UploadedFile.php index a44c664b4..86153ed49 100644 --- a/lib/symfony/http-foundation/File/UploadedFile.php +++ b/lib/symfony/http-foundation/File/UploadedFile.php @@ -214,13 +214,26 @@ class UploadedFile extends File */ public static function getMaxFilesize() { - $iniMax = strtolower(ini_get('upload_max_filesize')); + $sizePostMax = self::parseFilesize(ini_get('post_max_size')); + $sizeUploadMax = self::parseFilesize(ini_get('upload_max_filesize')); - if ('' === $iniMax) { - return PHP_INT_MAX; + return min($sizePostMax ?: PHP_INT_MAX, $sizeUploadMax ?: PHP_INT_MAX); + } + + /** + * Returns the given size from an ini value in bytes. + * + * @return int The given size in bytes + */ + private static function parseFilesize($size) + { + if ('' === $size) { + return 0; } - $max = ltrim($iniMax, '+'); + $size = strtolower($size); + + $max = ltrim($size, '+'); if (0 === strpos($max, '0x')) { $max = \intval($max, 16); } elseif (0 === strpos($max, '0')) { @@ -229,7 +242,7 @@ class UploadedFile extends File $max = (int) $max; } - switch (substr($iniMax, -1)) { + switch (substr($size, -1)) { case 't': $max *= 1024; // no break case 'g': $max *= 1024; diff --git a/lib/symfony/http-foundation/FileBag.php b/lib/symfony/http-foundation/FileBag.php index ca849b3d7..024fadf20 100644 --- a/lib/symfony/http-foundation/FileBag.php +++ b/lib/symfony/http-foundation/FileBag.php @@ -75,8 +75,8 @@ class FileBag extends ParameterBag return $file; } - $file = $this->fixPhpFilesArray($file); if (\is_array($file)) { + $file = $this->fixPhpFilesArray($file); $keys = array_keys($file); sort($keys); @@ -109,14 +109,12 @@ class FileBag extends ParameterBag * It's safe to pass an already converted array, in which case this method * just returns the original array unmodified. * + * @param array $data + * * @return array */ protected function fixPhpFilesArray($data) { - if (!\is_array($data)) { - return $data; - } - $keys = array_keys($data); sort($keys); diff --git a/lib/symfony/http-foundation/HeaderBag.php b/lib/symfony/http-foundation/HeaderBag.php index 9798173e6..35bd6ad8f 100644 --- a/lib/symfony/http-foundation/HeaderBag.php +++ b/lib/symfony/http-foundation/HeaderBag.php @@ -121,7 +121,15 @@ class HeaderBag implements \IteratorAggregate, \Countable } if ($first) { - return \count($headers[$key]) ? $headers[$key][0] : $default; + if (!$headers[$key]) { + return $default; + } + + if (null === $headers[$key][0]) { + return null; + } + + return (string) $headers[$key][0]; } return $headers[$key]; diff --git a/lib/symfony/http-foundation/JsonResponse.php b/lib/symfony/http-foundation/JsonResponse.php index a9bdac30f..b0e765167 100644 --- a/lib/symfony/http-foundation/JsonResponse.php +++ b/lib/symfony/http-foundation/JsonResponse.php @@ -100,7 +100,7 @@ class JsonResponse extends Response public function setCallback($callback = null) { if (null !== $callback) { - // partially taken from http://www.geekality.net/2011/08/03/valid-javascript-identifier/ + // partially taken from https://geekality.net/2011/08/03/valid-javascript-identifier/ // partially taken from https://github.com/willdurand/JsonpCallbackValidator // JsonpCallbackValidator is released under the MIT License. See https://github.com/willdurand/JsonpCallbackValidator/blob/v1.1.0/LICENSE for details. // (c) William Durand diff --git a/lib/symfony/http-foundation/ParameterBag.php b/lib/symfony/http-foundation/ParameterBag.php index f05e4a215..194ba2c6c 100644 --- a/lib/symfony/http-foundation/ParameterBag.php +++ b/lib/symfony/http-foundation/ParameterBag.php @@ -191,7 +191,7 @@ class ParameterBag implements \IteratorAggregate, \Countable * @param int $filter FILTER_* constant * @param mixed $options Filter options * - * @see http://php.net/manual/en/function.filter-var.php + * @see https://php.net/filter-var * * @return mixed */ diff --git a/lib/symfony/http-foundation/RedirectResponse.php b/lib/symfony/http-foundation/RedirectResponse.php index 51fd869ab..4e3cb4f77 100644 --- a/lib/symfony/http-foundation/RedirectResponse.php +++ b/lib/symfony/http-foundation/RedirectResponse.php @@ -30,7 +30,7 @@ class RedirectResponse extends Response * * @throws \InvalidArgumentException * - * @see http://tools.ietf.org/html/rfc2616#section-10.3 + * @see https://tools.ietf.org/html/rfc2616#section-10.3 */ public function __construct($url, $status = 302, $headers = []) { diff --git a/lib/symfony/http-foundation/Request.php b/lib/symfony/http-foundation/Request.php index 7185d75e9..3fc7b71e6 100644 --- a/lib/symfony/http-foundation/Request.php +++ b/lib/symfony/http-foundation/Request.php @@ -97,49 +97,49 @@ class Request /** * Custom parameters. * - * @var \Symfony\Component\HttpFoundation\ParameterBag + * @var ParameterBag */ public $attributes; /** * Request body parameters ($_POST). * - * @var \Symfony\Component\HttpFoundation\ParameterBag + * @var ParameterBag */ public $request; /** * Query string parameters ($_GET). * - * @var \Symfony\Component\HttpFoundation\ParameterBag + * @var ParameterBag */ public $query; /** * Server and execution environment parameters ($_SERVER). * - * @var \Symfony\Component\HttpFoundation\ServerBag + * @var ServerBag */ public $server; /** * Uploaded files ($_FILES). * - * @var \Symfony\Component\HttpFoundation\FileBag + * @var FileBag */ public $files; /** * Cookies ($_COOKIE). * - * @var \Symfony\Component\HttpFoundation\ParameterBag + * @var ParameterBag */ public $cookies; /** * Headers (taken from the $_SERVER). * - * @var \Symfony\Component\HttpFoundation\HeaderBag + * @var HeaderBag */ public $headers; @@ -199,7 +199,7 @@ class Request protected $format; /** - * @var \Symfony\Component\HttpFoundation\Session\SessionInterface + * @var SessionInterface */ protected $session; @@ -528,6 +528,10 @@ class Request try { $content = $this->getContent(); } catch (\LogicException $e) { + if (\PHP_VERSION_ID >= 70400) { + throw $e; + } + return trigger_error($e, E_USER_ERROR); } @@ -915,7 +919,7 @@ class Request * @return string|null The client IP address * * @see getClientIps() - * @see http://en.wikipedia.org/wiki/X-Forwarded-For + * @see https://wikipedia.org/wiki/X-Forwarded-For */ public function getClientIp() { @@ -1204,7 +1208,7 @@ class Request // A reference to the same base directory or an empty subdirectory must be prefixed with "./". // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used // as the first segment of a relative-path reference, as it would be mistaken for a scheme name - // (see http://tools.ietf.org/html/rfc3986#section-4.2). + // (see https://tools.ietf.org/html/rfc3986#section-4.2). return !isset($path[0]) || '/' === $path[0] || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos) ? "./$path" : $path; @@ -1449,6 +1453,8 @@ class Request return $format; } } + + return null; } /** @@ -1823,7 +1829,7 @@ class Request * It works if your JavaScript library sets an X-Requested-With HTTP header. * It is known to work with common JavaScript frameworks: * - * @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript + * @see https://wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript * * @return bool true if the request is an XMLHttpRequest, false otherwise */ @@ -1835,9 +1841,9 @@ class Request /* * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24) * - * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd). + * Code subject to the new BSD license (https://framework.zend.com/license). * - * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) + * Copyright (c) 2005-2010 Zend Technologies USA Inc. (https://www.zend.com/) */ protected function prepareRequestUri() diff --git a/lib/symfony/http-foundation/RequestMatcher.php b/lib/symfony/http-foundation/RequestMatcher.php index cadf70c5b..3f5149579 100644 --- a/lib/symfony/http-foundation/RequestMatcher.php +++ b/lib/symfony/http-foundation/RequestMatcher.php @@ -53,7 +53,6 @@ class RequestMatcher implements RequestMatcherInterface * @param string|null $host * @param string|string[]|null $methods * @param string|string[]|null $ips - * @param array $attributes * @param string|string[]|null $schemes */ public function __construct($path = null, $host = null, $methods = null, $ips = null, array $attributes = [], $schemes = null) diff --git a/lib/symfony/http-foundation/RequestStack.php b/lib/symfony/http-foundation/RequestStack.php index 885d78a50..244a77d63 100644 --- a/lib/symfony/http-foundation/RequestStack.php +++ b/lib/symfony/http-foundation/RequestStack.php @@ -47,7 +47,7 @@ class RequestStack public function pop() { if (!$this->requests) { - return; + return null; } return array_pop($this->requests); @@ -73,7 +73,7 @@ class RequestStack public function getMasterRequest() { if (!$this->requests) { - return; + return null; } return $this->requests[0]; @@ -95,7 +95,7 @@ class RequestStack $pos = \count($this->requests) - 2; if (!isset($this->requests[$pos])) { - return; + return null; } return $this->requests[$pos]; diff --git a/lib/symfony/http-foundation/Response.php b/lib/symfony/http-foundation/Response.php index 4ab05066f..26e3a3378 100644 --- a/lib/symfony/http-foundation/Response.php +++ b/lib/symfony/http-foundation/Response.php @@ -88,7 +88,7 @@ class Response const HTTP_NETWORK_AUTHENTICATION_REQUIRED = 511; // RFC6585 /** - * @var \Symfony\Component\HttpFoundation\ResponseHeaderBag + * @var ResponseHeaderBag */ public $headers; @@ -121,7 +121,7 @@ class Response * Status codes translation table. * * The list of codes is complete according to the - * {@link http://www.iana.org/assignments/http-status-codes/ Hypertext Transfer Protocol (HTTP) Status Code Registry} + * {@link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml Hypertext Transfer Protocol (HTTP) Status Code Registry} * (last updated 2016-03-01). * * Unless otherwise noted, the status code is defined in RFC2616. @@ -342,7 +342,7 @@ class Response // cookies foreach ($this->headers->getCookies() as $cookie) { - header('Set-Cookie: '.$cookie->getName().strstr($cookie, '='), false, $this->statusCode); + header('Set-Cookie: '.$cookie, false, $this->statusCode); } // status @@ -407,7 +407,7 @@ class Response /** * Gets the current response content. * - * @return string Content + * @return string|false */ public function getContent() { @@ -790,6 +790,8 @@ class Response if (null !== $this->getExpires()) { return (int) $this->getExpires()->format('U') - (int) $this->getDate()->format('U'); } + + return null; } /** @@ -846,6 +848,8 @@ class Response if (null !== $maxAge = $this->getMaxAge()) { return $maxAge - $this->getAge(); } + + return null; } /** @@ -1025,7 +1029,7 @@ class Response * * @return $this * - * @see http://tools.ietf.org/html/rfc2616#section-10.3.5 + * @see https://tools.ietf.org/html/rfc2616#section-10.3.5 * * @final since version 3.3 */ @@ -1133,7 +1137,7 @@ class Response * * @return bool * - * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html * * @final since version 3.2 */ diff --git a/lib/symfony/http-foundation/ServerBag.php b/lib/symfony/http-foundation/ServerBag.php index 90da49fae..4c82b1774 100644 --- a/lib/symfony/http-foundation/ServerBag.php +++ b/lib/symfony/http-foundation/ServerBag.php @@ -79,7 +79,7 @@ class ServerBag extends ParameterBag /* * XXX: Since there is no PHP_AUTH_BEARER in PHP predefined variables, * I'll just set $headers['AUTHORIZATION'] here. - * http://php.net/manual/en/reserved.variables.server.php + * https://php.net/reserved.variables.server */ $headers['AUTHORIZATION'] = $authorizationHeader; } diff --git a/lib/symfony/http-foundation/Session/Attribute/NamespacedAttributeBag.php b/lib/symfony/http-foundation/Session/Attribute/NamespacedAttributeBag.php index bbf2e39c8..07885e7fb 100644 --- a/lib/symfony/http-foundation/Session/Attribute/NamespacedAttributeBag.php +++ b/lib/symfony/http-foundation/Session/Attribute/NamespacedAttributeBag.php @@ -97,7 +97,7 @@ class NamespacedAttributeBag extends AttributeBag * @param string $name Key name * @param bool $writeContext Write context, default false * - * @return array + * @return array|null */ protected function &resolveAttributePath($name, $writeContext = false) { diff --git a/lib/symfony/http-foundation/Session/Storage/Handler/MemcachedSessionHandler.php b/lib/symfony/http-foundation/Session/Storage/Handler/MemcachedSessionHandler.php index 1db590b36..a399be5fd 100644 --- a/lib/symfony/http-foundation/Session/Storage/Handler/MemcachedSessionHandler.php +++ b/lib/symfony/http-foundation/Session/Storage/Handler/MemcachedSessionHandler.php @@ -15,7 +15,7 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; * Memcached based session storage handler based on the Memcached class * provided by the PHP memcached extension. * - * @see http://php.net/memcached + * @see https://php.net/memcached * * @author Drak */ @@ -40,9 +40,6 @@ class MemcachedSessionHandler extends AbstractSessionHandler * * prefix: The prefix to use for the memcached keys in order to avoid collision * * expiretime: The time to live in seconds. * - * @param \Memcached $memcached A \Memcached instance - * @param array $options An associative array of Memcached options - * * @throws \InvalidArgumentException When unsupported options are passed */ public function __construct(\Memcached $memcached, array $options = []) @@ -58,7 +55,7 @@ class MemcachedSessionHandler extends AbstractSessionHandler } /** - * {@inheritdoc} + * @return bool */ public function close() { @@ -74,7 +71,7 @@ class MemcachedSessionHandler extends AbstractSessionHandler } /** - * {@inheritdoc} + * @return bool */ public function updateTimestamp($sessionId, $data) { @@ -102,7 +99,7 @@ class MemcachedSessionHandler extends AbstractSessionHandler } /** - * {@inheritdoc} + * @return bool */ public function gc($maxlifetime) { diff --git a/lib/symfony/http-foundation/Session/Storage/Handler/MongoDbSessionHandler.php b/lib/symfony/http-foundation/Session/Storage/Handler/MongoDbSessionHandler.php index ddedacffb..1dd724066 100644 --- a/lib/symfony/http-foundation/Session/Storage/Handler/MongoDbSessionHandler.php +++ b/lib/symfony/http-foundation/Session/Storage/Handler/MongoDbSessionHandler.php @@ -56,7 +56,7 @@ class MongoDbSessionHandler extends AbstractSessionHandler * { "expireAfterSeconds": 0 } * ) * - * More details on: http://docs.mongodb.org/manual/tutorial/expire-data/ + * More details on: https://docs.mongodb.org/manual/tutorial/expire-data/ * * If you use such an index, you can drop `gc_probability` to 0 since * no garbage-collection is required. diff --git a/lib/symfony/http-foundation/Session/Storage/Handler/NativeFileSessionHandler.php b/lib/symfony/http-foundation/Session/Storage/Handler/NativeFileSessionHandler.php index 04bcbbfe3..8b7615ec1 100644 --- a/lib/symfony/http-foundation/Session/Storage/Handler/NativeFileSessionHandler.php +++ b/lib/symfony/http-foundation/Session/Storage/Handler/NativeFileSessionHandler.php @@ -23,7 +23,7 @@ class NativeFileSessionHandler extends NativeSessionHandler * Default null will leave setting as defined by PHP. * '/path', 'N;/path', or 'N;octal-mode;/path * - * @see https://php.net/manual/session.configuration.php#ini.session.save-path for further details. + * @see https://php.net/session.configuration#ini.session.save-path for further details. * * @throws \InvalidArgumentException On invalid $savePath * @throws \RuntimeException When failing to create the save directory diff --git a/lib/symfony/http-foundation/Session/Storage/Handler/NativeSessionHandler.php b/lib/symfony/http-foundation/Session/Storage/Handler/NativeSessionHandler.php index 9be4528ae..5159b1e35 100644 --- a/lib/symfony/http-foundation/Session/Storage/Handler/NativeSessionHandler.php +++ b/lib/symfony/http-foundation/Session/Storage/Handler/NativeSessionHandler.php @@ -13,7 +13,7 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; /** * @deprecated since version 3.4, to be removed in 4.0. Use \SessionHandler instead. - * @see http://php.net/sessionhandler + * @see https://php.net/sessionhandler */ class NativeSessionHandler extends \SessionHandler { diff --git a/lib/symfony/http-foundation/Session/Storage/Handler/NullSessionHandler.php b/lib/symfony/http-foundation/Session/Storage/Handler/NullSessionHandler.php index 8d193155b..3ba9378ca 100644 --- a/lib/symfony/http-foundation/Session/Storage/Handler/NullSessionHandler.php +++ b/lib/symfony/http-foundation/Session/Storage/Handler/NullSessionHandler.php @@ -67,7 +67,7 @@ class NullSessionHandler extends AbstractSessionHandler } /** - * {@inheritdoc} + * @return bool */ public function gc($maxlifetime) { diff --git a/lib/symfony/http-foundation/Session/Storage/Handler/PdoSessionHandler.php b/lib/symfony/http-foundation/Session/Storage/Handler/PdoSessionHandler.php index 9369740eb..f9e5d1e8f 100644 --- a/lib/symfony/http-foundation/Session/Storage/Handler/PdoSessionHandler.php +++ b/lib/symfony/http-foundation/Session/Storage/Handler/PdoSessionHandler.php @@ -32,7 +32,7 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; * Saving it in a character column could corrupt the data. You can use createTable() * to initialize a correctly defined table. * - * @see http://php.net/sessionhandlerinterface + * @see https://php.net/sessionhandlerinterface * * @author Fabien Potencier * @author Michael Williams @@ -286,7 +286,7 @@ class PdoSessionHandler extends AbstractSessionHandler } /** - * {@inheritdoc} + * @return bool */ public function gc($maxlifetime) { @@ -538,7 +538,7 @@ class PdoSessionHandler extends AbstractSessionHandler * PDO::rollback or PDO::inTransaction for SQLite. * * Also MySQLs default isolation, REPEATABLE READ, causes deadlock for different sessions - * due to http://www.mysqlperformanceblog.com/2013/12/12/one-more-innodb-gap-lock-to-avoid/ . + * due to https://percona.com/blog/2013/12/12/one-more-innodb-gap-lock-to-avoid/ . * So we change it to READ COMMITTED. */ private function beginTransaction() @@ -864,7 +864,7 @@ class PdoSessionHandler extends AbstractSessionHandler break; case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='): // MERGE is only available since SQL Server 2008 and must be terminated by semicolon - // It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx + // It also requires HOLDLOCK according to https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/ $mergeSql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ". "WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ". "WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;"; @@ -877,7 +877,7 @@ class PdoSessionHandler extends AbstractSessionHandler "ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)"; break; default: - // MERGE is not supported with LOBs: http://www.oracle.com/technetwork/articles/fuecks-lobs-095315.html + // MERGE is not supported with LOBs: https://oracle.com/technetwork/articles/fuecks-lobs-095315.html return null; } diff --git a/lib/symfony/http-foundation/Session/Storage/Handler/StrictSessionHandler.php b/lib/symfony/http-foundation/Session/Storage/Handler/StrictSessionHandler.php index 83a1f2c06..fab8e9a16 100644 --- a/lib/symfony/http-foundation/Session/Storage/Handler/StrictSessionHandler.php +++ b/lib/symfony/http-foundation/Session/Storage/Handler/StrictSessionHandler.php @@ -94,7 +94,7 @@ class StrictSessionHandler extends AbstractSessionHandler } /** - * {@inheritdoc} + * @return bool */ public function gc($maxlifetime) { diff --git a/lib/symfony/http-foundation/Session/Storage/NativeSessionStorage.php b/lib/symfony/http-foundation/Session/Storage/NativeSessionStorage.php index 809d7002c..4c5873728 100644 --- a/lib/symfony/http-foundation/Session/Storage/NativeSessionStorage.php +++ b/lib/symfony/http-foundation/Session/Storage/NativeSessionStorage.php @@ -54,7 +54,7 @@ class NativeSessionStorage implements SessionStorageInterface * * List of options for $options array with their defaults. * - * @see http://php.net/session.configuration for options + * @see https://php.net/session.configuration for options * but we omit 'session.' from the beginning of the keys for convenience. * * ("auto_start", is not supported as it tells PHP to start a session before @@ -212,7 +212,7 @@ class NativeSessionStorage implements SessionStorageInterface $isRegenerated = session_regenerate_id($destroy); // The reference to $_SESSION in session bags is lost in PHP7 and we need to re-create it. - // @see https://bugs.php.net/bug.php?id=70013 + // @see https://bugs.php.net/70013 $this->loadSession(); return $isRegenerated; @@ -337,7 +337,7 @@ class NativeSessionStorage implements SessionStorageInterface * * @param array $options Session ini directives [key => value] * - * @see http://php.net/session.configuration + * @see https://php.net/session.configuration */ public function setOptions(array $options) { @@ -378,10 +378,10 @@ class NativeSessionStorage implements SessionStorageInterface * constructor, for a template see NativeFileSessionHandler or use handlers in * composer package drak/native-session * - * @see http://php.net/session-set-save-handler - * @see http://php.net/sessionhandlerinterface - * @see http://php.net/sessionhandler - * @see http://github.com/drak/NativeSession + * @see https://php.net/session-set-save-handler + * @see https://php.net/sessionhandlerinterface + * @see https://php.net/sessionhandler + * @see https://github.com/zikula/NativeSession * * @param \SessionHandlerInterface|null $saveHandler * @@ -430,7 +430,7 @@ class NativeSessionStorage implements SessionStorageInterface foreach ($bags as $bag) { $key = $bag->getStorageKey(); - $session[$key] = isset($session[$key]) ? $session[$key] : []; + $session[$key] = isset($session[$key]) && \is_array($session[$key]) ? $session[$key] : []; $bag->initialize($session[$key]); } diff --git a/lib/symfony/http-foundation/Session/Storage/Proxy/AbstractProxy.php b/lib/symfony/http-foundation/Session/Storage/Proxy/AbstractProxy.php index 09c92483c..0303729e7 100644 --- a/lib/symfony/http-foundation/Session/Storage/Proxy/AbstractProxy.php +++ b/lib/symfony/http-foundation/Session/Storage/Proxy/AbstractProxy.php @@ -31,7 +31,7 @@ abstract class AbstractProxy /** * Gets the session.save_handler name. * - * @return string + * @return string|null */ public function getSaveHandlerName() { diff --git a/lib/symfony/http-foundation/Session/Storage/Proxy/SessionHandlerProxy.php b/lib/symfony/http-foundation/Session/Storage/Proxy/SessionHandlerProxy.php index b11cc397a..e40712d93 100644 --- a/lib/symfony/http-foundation/Session/Storage/Proxy/SessionHandlerProxy.php +++ b/lib/symfony/http-foundation/Session/Storage/Proxy/SessionHandlerProxy.php @@ -76,7 +76,7 @@ class SessionHandlerProxy extends AbstractProxy implements \SessionHandlerInterf } /** - * {@inheritdoc} + * @return bool */ public function gc($maxlifetime) { diff --git a/lib/symfony/http-foundation/Session/Storage/SessionStorageInterface.php b/lib/symfony/http-foundation/Session/Storage/SessionStorageInterface.php index 66e8b33dd..eeb396a2f 100644 --- a/lib/symfony/http-foundation/Session/Storage/SessionStorageInterface.php +++ b/lib/symfony/http-foundation/Session/Storage/SessionStorageInterface.php @@ -77,7 +77,7 @@ interface SessionStorageInterface * only delete the session data from persistent storage. * * Care: When regenerating the session ID no locking is involved in PHP's - * session design. See https://bugs.php.net/bug.php?id=61470 for a discussion. + * session design. See https://bugs.php.net/61470 for a discussion. * So you must make sure the regenerated session is saved BEFORE sending the * headers with the new ID. Symfony's HttpKernel offers a listener for this. * See Symfony\Component\HttpKernel\EventListener\SaveSessionListener. diff --git a/lib/symfony/http-foundation/StreamedResponse.php b/lib/symfony/http-foundation/StreamedResponse.php index 8bc5fc91a..b9148ea87 100644 --- a/lib/symfony/http-foundation/StreamedResponse.php +++ b/lib/symfony/http-foundation/StreamedResponse.php @@ -136,8 +136,6 @@ class StreamedResponse extends Response /** * {@inheritdoc} - * - * @return false */ public function getContent() { diff --git a/lib/symfony/http-foundation/Tests/BinaryFileResponseTest.php b/lib/symfony/http-foundation/Tests/BinaryFileResponseTest.php index 853b4bb3d..fcad11def 100644 --- a/lib/symfony/http-foundation/Tests/BinaryFileResponseTest.php +++ b/lib/symfony/http-foundation/Tests/BinaryFileResponseTest.php @@ -46,11 +46,9 @@ class BinaryFileResponseTest extends ResponseTestCase $this->assertSame('fööö.html', $response->getFile()->getFilename()); } - /** - * @expectedException \LogicException - */ public function testSetContent() { + $this->expectException('LogicException'); $response = new BinaryFileResponse(__FILE__); $response->setContent('foo'); } @@ -109,7 +107,7 @@ class BinaryFileResponseTest extends ResponseTestCase $this->assertEquals(206, $response->getStatusCode()); $this->assertEquals($responseRange, $response->headers->get('Content-Range')); - $this->assertSame($length, $response->headers->get('Content-Length')); + $this->assertSame((string) $length, $response->headers->get('Content-Length')); } /** @@ -263,7 +261,7 @@ class BinaryFileResponseTest extends ResponseTestCase $this->expectOutputString(''); $response->sendContent(); - $this->assertContains('README.md', $response->headers->get('X-Sendfile')); + $this->assertStringContainsString('README.md', $response->headers->get('X-Sendfile')); } public function provideXSendfileFiles() diff --git a/lib/symfony/http-foundation/Tests/CookieTest.php b/lib/symfony/http-foundation/Tests/CookieTest.php index aaf2edb38..169f91787 100644 --- a/lib/symfony/http-foundation/Tests/CookieTest.php +++ b/lib/symfony/http-foundation/Tests/CookieTest.php @@ -24,10 +24,9 @@ use Symfony\Component\HttpFoundation\Cookie; */ class CookieTest extends TestCase { - public function invalidNames() + public function namesWithSpecialCharacters() { return [ - [''], [',MyName'], [';MyName'], [' MyName'], @@ -40,19 +39,31 @@ class CookieTest extends TestCase } /** - * @dataProvider invalidNames - * @expectedException \InvalidArgumentException + * @dataProvider namesWithSpecialCharacters */ - public function testInstantiationThrowsExceptionIfCookieNameContainsInvalidCharacters($name) + public function testInstantiationThrowsExceptionIfRawCookieNameContainsSpecialCharacters($name) { - new Cookie($name); + $this->expectException('InvalidArgumentException'); + new Cookie($name, null, 0, null, null, null, false, true); } /** - * @expectedException \InvalidArgumentException + * @dataProvider namesWithSpecialCharacters */ + public function testInstantiationSucceedNonRawCookieNameContainsSpecialCharacters($name) + { + $this->assertInstanceOf(Cookie::class, new Cookie($name)); + } + + public function testInstantiationThrowsExceptionIfCookieNameIsEmpty() + { + $this->expectException('InvalidArgumentException'); + new Cookie(''); + } + public function testInvalidExpiration() { + $this->expectException('InvalidArgumentException'); new Cookie('MyCookie', 'foo', 'bar'); } @@ -121,7 +132,7 @@ class CookieTest extends TestCase $cookie = new Cookie('foo', 'bar', $value); $expire = strtotime($value); - $this->assertEquals($expire, $cookie->getExpiresTime(), '->getExpiresTime() returns the expire date', 1); + $this->assertEqualsWithDelta($expire, $cookie->getExpiresTime(), 1, '->getExpiresTime() returns the expire date'); } public function testGetDomain() diff --git a/lib/symfony/http-foundation/Tests/ExpressionRequestMatcherTest.php b/lib/symfony/http-foundation/Tests/ExpressionRequestMatcherTest.php index 2afdade67..8a389329e 100644 --- a/lib/symfony/http-foundation/Tests/ExpressionRequestMatcherTest.php +++ b/lib/symfony/http-foundation/Tests/ExpressionRequestMatcherTest.php @@ -18,11 +18,9 @@ use Symfony\Component\HttpFoundation\Request; class ExpressionRequestMatcherTest extends TestCase { - /** - * @expectedException \LogicException - */ public function testWhenNoExpressionIsSet() { + $this->expectException('LogicException'); $expressionRequestMatcher = new ExpressionRequestMatcher(); $expressionRequestMatcher->matches(new Request()); } diff --git a/lib/symfony/http-foundation/Tests/File/FileTest.php b/lib/symfony/http-foundation/Tests/File/FileTest.php index caf202992..b463aadf8 100644 --- a/lib/symfony/http-foundation/Tests/File/FileTest.php +++ b/lib/symfony/http-foundation/Tests/File/FileTest.php @@ -64,7 +64,7 @@ class FileTest extends TestCase public function testConstructWhenFileNotExists() { - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); new File(__DIR__.'/Fixtures/not_here'); } diff --git a/lib/symfony/http-foundation/Tests/File/MimeType/MimeTypeTest.php b/lib/symfony/http-foundation/Tests/File/MimeType/MimeTypeTest.php index bb88807ab..0418726b5 100644 --- a/lib/symfony/http-foundation/Tests/File/MimeType/MimeTypeTest.php +++ b/lib/symfony/http-foundation/Tests/File/MimeType/MimeTypeTest.php @@ -20,7 +20,16 @@ use Symfony\Component\HttpFoundation\File\MimeType\MimeTypeGuesser; */ class MimeTypeTest extends TestCase { - protected $path; + public function testGuessWithLeadingDash() + { + $cwd = getcwd(); + chdir(__DIR__.'/../Fixtures'); + try { + $this->assertEquals('image/gif', MimeTypeGuesser::getInstance()->guess('-test')); + } finally { + chdir($cwd); + } + } public function testGuessImageWithoutExtension() { @@ -29,7 +38,7 @@ class MimeTypeTest extends TestCase public function testGuessImageWithDirectory() { - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/directory'); } @@ -53,7 +62,7 @@ class MimeTypeTest extends TestCase public function testGuessWithIncorrectPath() { - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); MimeTypeGuesser::getInstance()->guess(__DIR__.'/../Fixtures/not_here'); } @@ -72,7 +81,7 @@ class MimeTypeTest extends TestCase @chmod($path, 0333); if ('0333' == substr(sprintf('%o', fileperms($path)), -4)) { - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException'); + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException'); MimeTypeGuesser::getInstance()->guess($path); } else { $this->markTestSkipped('Can not verify chmod operations, change of file permissions failed'); diff --git a/lib/symfony/http-foundation/Tests/File/UploadedFileTest.php b/lib/symfony/http-foundation/Tests/File/UploadedFileTest.php index 5a37cda35..2ea924bac 100644 --- a/lib/symfony/http-foundation/Tests/File/UploadedFileTest.php +++ b/lib/symfony/http-foundation/Tests/File/UploadedFileTest.php @@ -25,7 +25,7 @@ class UploadedFileTest extends TestCase public function testConstructWhenFileNotExists() { - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); new UploadedFile( __DIR__.'/Fixtures/not_here', @@ -142,11 +142,9 @@ class UploadedFileTest extends TestCase $this->assertEquals('gif', $file->getClientOriginalExtension()); } - /** - * @expectedException \Symfony\Component\HttpFoundation\File\Exception\FileException - */ public function testMoveLocalFileIsNotAllowed() { + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileException'); $file = new UploadedFile( __DIR__.'/Fixtures/test.gif', 'original.gif', @@ -155,7 +153,7 @@ class UploadedFileTest extends TestCase UPLOAD_ERR_OK ); - $movedFile = $file->move(__DIR__.'/Fixtures/directory'); + $file->move(__DIR__.'/Fixtures/directory'); } public function testMoveLocalFileIsAllowedInTestMode() @@ -283,4 +281,18 @@ class UploadedFileTest extends TestCase $this->assertFalse($file->isValid()); } + + public function testGetMaxFilesize() + { + $size = UploadedFile::getMaxFilesize(); + + $this->assertIsInt($size); + $this->assertGreaterThan(0, $size); + + if (0 === (int) ini_get('post_max_size') && 0 === (int) ini_get('upload_max_filesize')) { + $this->assertSame(PHP_INT_MAX, $size); + } else { + $this->assertLessThan(PHP_INT_MAX, $size); + } + } } diff --git a/lib/symfony/http-foundation/Tests/FileBagTest.php b/lib/symfony/http-foundation/Tests/FileBagTest.php index 0b6d66042..a3882bc86 100644 --- a/lib/symfony/http-foundation/Tests/FileBagTest.php +++ b/lib/symfony/http-foundation/Tests/FileBagTest.php @@ -23,11 +23,9 @@ use Symfony\Component\HttpFoundation\FileBag; */ class FileBagTest extends TestCase { - /** - * @expectedException \InvalidArgumentException - */ public function testFileMustBeAnArrayOrUploadedFile() { + $this->expectException('InvalidArgumentException'); new FileBag(['file' => 'foo']); } diff --git a/lib/symfony/http-foundation/Tests/Fixtures/response-functional/cookie_urlencode.expected b/lib/symfony/http-foundation/Tests/Fixtures/response-functional/cookie_urlencode.expected index 14e44a398..17a9efc66 100644 --- a/lib/symfony/http-foundation/Tests/Fixtures/response-functional/cookie_urlencode.expected +++ b/lib/symfony/http-foundation/Tests/Fixtures/response-functional/cookie_urlencode.expected @@ -4,7 +4,8 @@ Array [0] => Content-Type: text/plain; charset=utf-8 [1] => Cache-Control: no-cache, private [2] => Date: Sat, 12 Nov 1955 20:04:00 GMT - [3] => Set-Cookie: ?*():@&+$/%#[]=%3F%2A%28%29%3A%40%26%2B%24%2F%25%23%5B%5D; path=/ + [3] => Set-Cookie: %3D%2C%3B%20%09%0D%0A%0B%0C=%3D%2C%3B%20%09%0D%0A%0B%0C; path=/ [4] => Set-Cookie: ?*():@&+$/%#[]=%3F%2A%28%29%3A%40%26%2B%24%2F%25%23%5B%5D; path=/ + [5] => Set-Cookie: ?*():@&+$/%#[]=%3F%2A%28%29%3A%40%26%2B%24%2F%25%23%5B%5D; path=/ ) shutdown diff --git a/lib/symfony/http-foundation/Tests/Fixtures/response-functional/cookie_urlencode.php b/lib/symfony/http-foundation/Tests/Fixtures/response-functional/cookie_urlencode.php index 05b9af30d..9ffb0dfec 100644 --- a/lib/symfony/http-foundation/Tests/Fixtures/response-functional/cookie_urlencode.php +++ b/lib/symfony/http-foundation/Tests/Fixtures/response-functional/cookie_urlencode.php @@ -4,9 +4,12 @@ use Symfony\Component\HttpFoundation\Cookie; $r = require __DIR__.'/common.inc'; -$str = '?*():@&+$/%#[]'; +$str1 = "=,; \t\r\n\v\f"; +$r->headers->setCookie(new Cookie($str1, $str1, 0, '', null, false, false, false, null)); -$r->headers->setCookie(new Cookie($str, $str, 0, '', null, false, false)); +$str2 = '?*():@&+$/%#[]'; + +$r->headers->setCookie(new Cookie($str2, $str2, 0, '', null, false, false, false, null)); $r->sendHeaders(); -setcookie($str, $str, 0, '/'); +setcookie($str2, $str2, 0, '/'); diff --git a/lib/symfony/http-foundation/Tests/Fixtures/response-functional/invalid_cookie_name.php b/lib/symfony/http-foundation/Tests/Fixtures/response-functional/invalid_cookie_name.php index 3fe157184..3acf86039 100644 --- a/lib/symfony/http-foundation/Tests/Fixtures/response-functional/invalid_cookie_name.php +++ b/lib/symfony/http-foundation/Tests/Fixtures/response-functional/invalid_cookie_name.php @@ -5,7 +5,7 @@ use Symfony\Component\HttpFoundation\Cookie; $r = require __DIR__.'/common.inc'; try { - $r->headers->setCookie(new Cookie('Hello + world', 'hodor')); + $r->headers->setCookie(new Cookie('Hello + world', 'hodor', 0, null, null, null, false, true)); } catch (\InvalidArgumentException $e) { echo $e->getMessage(); } diff --git a/lib/symfony/http-foundation/Tests/HeaderBagTest.php b/lib/symfony/http-foundation/Tests/HeaderBagTest.php index 6c4915f2e..cabe038bd 100644 --- a/lib/symfony/http-foundation/Tests/HeaderBagTest.php +++ b/lib/symfony/http-foundation/Tests/HeaderBagTest.php @@ -48,13 +48,18 @@ class HeaderBagTest extends TestCase $this->assertInstanceOf('DateTime', $headerDate); } - /** - * @expectedException \RuntimeException - */ + public function testGetDateNull() + { + $bag = new HeaderBag(['foo' => null]); + $headerDate = $bag->getDate('foo'); + $this->assertNull($headerDate); + } + public function testGetDateException() { + $this->expectException('RuntimeException'); $bag = new HeaderBag(['foo' => 'Tue']); - $headerDate = $bag->getDate('foo'); + $bag->getDate('foo'); } public function testGetCacheControlHeader() @@ -98,6 +103,9 @@ class HeaderBagTest extends TestCase $bag->set('foo', 'bor', false); $this->assertEquals('bar', $bag->get('foo'), '->get return first value'); $this->assertEquals(['bar', 'bor'], $bag->get('foo', 'nope', false), '->get return all values as array'); + + $bag->set('baz', null); + $this->assertNull($bag->get('baz', 'nope'), '->get return null although different default value is given'); } public function testSetAssociativeArray() diff --git a/lib/symfony/http-foundation/Tests/IpUtilsTest.php b/lib/symfony/http-foundation/Tests/IpUtilsTest.php index c7f76b5de..d3b262e04 100644 --- a/lib/symfony/http-foundation/Tests/IpUtilsTest.php +++ b/lib/symfony/http-foundation/Tests/IpUtilsTest.php @@ -73,11 +73,11 @@ class IpUtilsTest extends TestCase } /** - * @expectedException \RuntimeException * @requires extension sockets */ public function testAnIpv6WithOptionDisabledIpv6() { + $this->expectException('RuntimeException'); if (\defined('AF_INET6')) { $this->markTestSkipped('Only works when PHP is compiled with the option "disable-ipv6".'); } diff --git a/lib/symfony/http-foundation/Tests/JsonResponseTest.php b/lib/symfony/http-foundation/Tests/JsonResponseTest.php index ef0346cbe..9642dc28d 100644 --- a/lib/symfony/http-foundation/Tests/JsonResponseTest.php +++ b/lib/symfony/http-foundation/Tests/JsonResponseTest.php @@ -52,8 +52,8 @@ class JsonResponseTest extends TestCase $this->assertSame('0', $response->getContent()); $response = new JsonResponse(0.1); - $this->assertEquals('0.1', $response->getContent()); - $this->assertInternalType('string', $response->getContent()); + $this->assertEquals(0.1, $response->getContent()); + $this->assertIsString($response->getContent()); $response = new JsonResponse(true); $this->assertSame('true', $response->getContent()); @@ -141,8 +141,8 @@ class JsonResponseTest extends TestCase $response = JsonResponse::create(0.1); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); - $this->assertEquals('0.1', $response->getContent()); - $this->assertInternalType('string', $response->getContent()); + $this->assertEquals(0.1, $response->getContent()); + $this->assertIsString($response->getContent()); $response = JsonResponse::create(true); $this->assertInstanceOf('Symfony\Component\HttpFoundation\JsonResponse', $response); @@ -216,29 +216,23 @@ class JsonResponseTest extends TestCase $this->assertSame('{"foo":"bar"}', $response->getContent()); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetCallbackInvalidIdentifier() { + $this->expectException('InvalidArgumentException'); $response = new JsonResponse('foo'); $response->setCallback('+invalid'); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetContent() { + $this->expectException('InvalidArgumentException'); JsonResponse::create("\xB1\x31"); } - /** - * @expectedException \Exception - * @expectedExceptionMessage This error is expected - */ public function testSetContentJsonSerializeError() { + $this->expectException('Exception'); + $this->expectExceptionMessage('This error is expected'); if (!interface_exists('JsonSerializable', false)) { $this->markTestSkipped('JsonSerializable is required.'); } diff --git a/lib/symfony/http-foundation/Tests/RedirectResponseTest.php b/lib/symfony/http-foundation/Tests/RedirectResponseTest.php index 5f6a8ac08..e1ff3bf2b 100644 --- a/lib/symfony/http-foundation/Tests/RedirectResponseTest.php +++ b/lib/symfony/http-foundation/Tests/RedirectResponseTest.php @@ -26,20 +26,16 @@ class RedirectResponseTest extends TestCase )); } - /** - * @expectedException \InvalidArgumentException - */ public function testRedirectResponseConstructorNullUrl() { - $response = new RedirectResponse(null); + $this->expectException('InvalidArgumentException'); + new RedirectResponse(null); } - /** - * @expectedException \InvalidArgumentException - */ public function testRedirectResponseConstructorWrongStatusCode() { - $response = new RedirectResponse('foo.bar', 404); + $this->expectException('InvalidArgumentException'); + new RedirectResponse('foo.bar', 404); } public function testGenerateLocationHeader() @@ -65,11 +61,9 @@ class RedirectResponseTest extends TestCase $this->assertEquals('baz.beep', $response->getTargetUrl()); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetTargetUrlNull() { + $this->expectException('InvalidArgumentException'); $response = new RedirectResponse('foo.bar'); $response->setTargetUrl(null); } diff --git a/lib/symfony/http-foundation/Tests/RequestTest.php b/lib/symfony/http-foundation/Tests/RequestTest.php index 73d12cb3f..bf70a5f83 100644 --- a/lib/symfony/http-foundation/Tests/RequestTest.php +++ b/lib/symfony/http-foundation/Tests/RequestTest.php @@ -886,11 +886,9 @@ class RequestTest extends TestCase $this->assertEquals(80, $port, 'With only PROTO set and value is not recognized, getPort() defaults to 80.'); } - /** - * @expectedException \RuntimeException - */ public function testGetHostWithFakeHttpHostValue() { + $this->expectException('RuntimeException'); $request = new Request(); $request->initialize([], [], [], [], [], ['HTTP_HOST' => 'www.host.com?query=string']); $request->getHost(); @@ -1055,11 +1053,11 @@ class RequestTest extends TestCase } /** - * @expectedException \Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException * @dataProvider getClientIpsWithConflictingHeadersProvider */ public function testGetClientIpsWithConflictingHeaders($httpForwarded, $httpXForwardedFor) { + $this->expectException('Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException'); $request = new Request(); $server = [ @@ -1153,7 +1151,7 @@ class RequestTest extends TestCase { $req = new Request(); $retval = $req->getContent(true); - $this->assertInternalType('resource', $retval); + $this->assertIsResource($retval); $this->assertEquals('', fread($retval, 1)); $this->assertTrue(feof($retval)); } @@ -1163,7 +1161,7 @@ class RequestTest extends TestCase $req = new Request([], [], [], [], [], [], 'MyContent'); $resource = $req->getContent(true); - $this->assertInternalType('resource', $resource); + $this->assertIsResource($resource); $this->assertEquals('MyContent', stream_get_contents($resource)); } @@ -1179,11 +1177,11 @@ class RequestTest extends TestCase } /** - * @expectedException \LogicException * @dataProvider getContentCantBeCalledTwiceWithResourcesProvider */ public function testGetContentCantBeCalledTwiceWithResources($first, $second) { + $this->expectException('LogicException'); if (\PHP_VERSION_ID >= 50600) { $this->markTestSkipped('PHP >= 5.6 allows to open php://input several times.'); } @@ -1551,7 +1549,6 @@ class RequestTest extends TestCase $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.8, en; q=0.6'); $this->assertEquals(['zh', 'en_US', 'en'], $request->getLanguages()); - $this->assertEquals(['zh', 'en_US', 'en'], $request->getLanguages()); $request = new Request(); $request->headers->set('Accept-language', 'zh, en-us; q=0.6, en; q=0.8'); @@ -1633,14 +1630,14 @@ class RequestTest extends TestCase $asString = (string) $request; - $this->assertContains('Accept-Language: zh, en-us; q=0.8, en; q=0.6', $asString); - $this->assertContains('Cookie: Foo=Bar', $asString); + $this->assertStringContainsString('Accept-Language: zh, en-us; q=0.8, en; q=0.6', $asString); + $this->assertStringContainsString('Cookie: Foo=Bar', $asString); $request->cookies->set('Another', 'Cookie'); $asString = (string) $request; - $this->assertContains('Cookie: Foo=Bar; Another=Cookie', $asString); + $this->assertStringContainsString('Cookie: Foo=Bar; Another=Cookie', $asString); } public function testIsMethod() @@ -1968,20 +1965,20 @@ class RequestTest extends TestCase /** * @group legacy - * @expectedException \InvalidArgumentException */ public function testSetTrustedProxiesInvalidHeaderName() { + $this->expectException('InvalidArgumentException'); Request::create('http://example.com/'); Request::setTrustedHeaderName('bogus name', 'X_MY_FOR'); } /** * @group legacy - * @expectedException \InvalidArgumentException */ public function testGetTrustedProxiesInvalidHeaderName() { + $this->expectException('InvalidArgumentException'); Request::create('http://example.com/'); Request::getTrustedHeaderName('bogus name'); } @@ -2118,12 +2115,8 @@ class RequestTest extends TestCase $this->assertSame($expectedPort, $request->getPort()); } } else { - if (method_exists($this, 'expectException')) { - $this->expectException(SuspiciousOperationException::class); - $this->expectExceptionMessage('Invalid Host'); - } else { - $this->setExpectedException(SuspiciousOperationException::class, 'Invalid Host'); - } + $this->expectException(SuspiciousOperationException::class); + $this->expectExceptionMessage('Invalid Host'); $request->getHost(); } diff --git a/lib/symfony/http-foundation/Tests/ResponseHeaderBagTest.php b/lib/symfony/http-foundation/Tests/ResponseHeaderBagTest.php index 93aacf24d..d85f6e112 100644 --- a/lib/symfony/http-foundation/Tests/ResponseHeaderBagTest.php +++ b/lib/symfony/http-foundation/Tests/ResponseHeaderBagTest.php @@ -240,21 +240,17 @@ class ResponseHeaderBagTest extends TestCase $this->assertEquals([], $bag->getCookies()); } - /** - * @expectedException \InvalidArgumentException - */ public function testGetCookiesWithInvalidArgument() { + $this->expectException('InvalidArgumentException'); $bag = new ResponseHeaderBag(); $bag->getCookies('invalid_argument'); } - /** - * @expectedException \InvalidArgumentException - */ public function testMakeDispositionInvalidDisposition() { + $this->expectException('InvalidArgumentException'); $headers = new ResponseHeaderBag(); $headers->makeDisposition('invalid', 'foo.html'); @@ -298,10 +294,10 @@ class ResponseHeaderBagTest extends TestCase /** * @dataProvider provideMakeDispositionFail - * @expectedException \InvalidArgumentException */ public function testMakeDispositionFail($disposition, $filename) { + $this->expectException('InvalidArgumentException'); $headers = new ResponseHeaderBag(); $headers->makeDisposition($disposition, $filename); diff --git a/lib/symfony/http-foundation/Tests/ResponseTest.php b/lib/symfony/http-foundation/Tests/ResponseTest.php index 40200ee31..b846cdad3 100644 --- a/lib/symfony/http-foundation/Tests/ResponseTest.php +++ b/lib/symfony/http-foundation/Tests/ResponseTest.php @@ -369,6 +369,12 @@ class ResponseTest extends ResponseTestCase $this->assertNull($response->headers->get('Expires'), '->expire() removes the Expires header when the response is fresh'); } + public function testNullExpireHeader() + { + $response = new Response(null, 200, ['Expires' => null]); + $this->assertNull($response->getExpires()); + } + public function testGetTtl() { $response = new Response(); @@ -532,7 +538,6 @@ class ResponseTest extends ResponseTestCase $response->prepare($request); $this->assertEquals('', $response->getContent()); $this->assertFalse($response->headers->has('Content-Type')); - $this->assertFalse($response->headers->has('Content-Type')); $response->setContent('content'); $response->setStatusCode(304); @@ -582,7 +587,7 @@ class ResponseTest extends ResponseTestCase $this->fail('->setCache() throws an InvalidArgumentException if an option is not supported'); } catch (\Exception $e) { $this->assertInstanceOf('InvalidArgumentException', $e, '->setCache() throws an InvalidArgumentException if an option is not supported'); - $this->assertContains('"wrong option"', $e->getMessage()); + $this->assertStringContainsString('"wrong option"', $e->getMessage()); } $options = ['etag' => '"whatever"']; @@ -635,7 +640,7 @@ class ResponseTest extends ResponseTestCase ob_start(); $response->sendContent(); $string = ob_get_clean(); - $this->assertContains('test response rendering', $string); + $this->assertStringContainsString('test response rendering', $string); } public function testSetPublic() @@ -846,11 +851,11 @@ class ResponseTest extends ResponseTestCase } /** - * @expectedException \UnexpectedValueException * @dataProvider invalidContentProvider */ public function testSetContentInvalid($content) { + $this->expectException('UnexpectedValueException'); $response = new Response(); $response->setContent($content); } @@ -928,11 +933,11 @@ class ResponseTest extends ResponseTestCase } /** - * @see http://github.com/zendframework/zend-diactoros for the canonical source repository + * @see http://github.com/zendframework/zend-diactoros for the canonical source repository * - * @author Fábio Pacheco + * @author Fábio Pacheco * @copyright Copyright (c) 2015-2016 Zend Technologies USA Inc. (http://www.zend.com) - * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License + * @license https://github.com/zendframework/zend-diactoros/blob/master/LICENSE.md New BSD License */ public function ianaCodesReasonPhrasesProvider() { diff --git a/lib/symfony/http-foundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php b/lib/symfony/http-foundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php index 5ce6a9e5a..f0f43d05b 100644 --- a/lib/symfony/http-foundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php +++ b/lib/symfony/http-foundation/Tests/Session/Storage/Handler/MongoDbSessionHandlerTest.php @@ -11,6 +11,7 @@ namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler; +use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler; @@ -22,7 +23,7 @@ use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandl class MongoDbSessionHandlerTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_MockObject + * @var MockObject */ private $mongo; private $storage; @@ -62,19 +63,15 @@ class MongoDbSessionHandlerTest extends TestCase $this->storage = new MongoDbSessionHandler($this->mongo, $this->options); } - /** - * @expectedException \InvalidArgumentException - */ public function testConstructorShouldThrowExceptionForInvalidMongo() { + $this->expectException('InvalidArgumentException'); new MongoDbSessionHandler(new \stdClass(), $this->options); } - /** - * @expectedException \InvalidArgumentException - */ public function testConstructorShouldThrowExceptionForMissingOptions() { + $this->expectException('InvalidArgumentException'); new MongoDbSessionHandler($this->mongo, []); } diff --git a/lib/symfony/http-foundation/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php b/lib/symfony/http-foundation/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php index dc827d8ab..7de55798a 100644 --- a/lib/symfony/http-foundation/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php +++ b/lib/symfony/http-foundation/Tests/Session/Storage/Handler/NativeFileSessionHandlerTest.php @@ -41,9 +41,9 @@ class NativeFileSessionHandlerTest extends TestCase */ public function testConstructSavePath($savePath, $expectedSavePath, $path) { - $handler = new NativeFileSessionHandler($savePath); + new NativeFileSessionHandler($savePath); $this->assertEquals($expectedSavePath, ini_get('session.save_path')); - $this->assertTrue(is_dir(realpath($path))); + $this->assertDirectoryExists(realpath($path)); rmdir($path); } @@ -59,18 +59,16 @@ class NativeFileSessionHandlerTest extends TestCase ]; } - /** - * @expectedException \InvalidArgumentException - */ public function testConstructException() { - $handler = new NativeFileSessionHandler('something;invalid;with;too-many-args'); + $this->expectException('InvalidArgumentException'); + new NativeFileSessionHandler('something;invalid;with;too-many-args'); } public function testConstructDefault() { $path = ini_get('session.save_path'); - $storage = new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler()); + new NativeSessionStorage(['name' => 'TESTING'], new NativeFileSessionHandler()); $this->assertEquals($path, ini_get('session.save_path')); } diff --git a/lib/symfony/http-foundation/Tests/Session/Storage/Handler/NullSessionHandlerTest.php b/lib/symfony/http-foundation/Tests/Session/Storage/Handler/NullSessionHandlerTest.php index 0d246e1aa..f793db144 100644 --- a/lib/symfony/http-foundation/Tests/Session/Storage/Handler/NullSessionHandlerTest.php +++ b/lib/symfony/http-foundation/Tests/Session/Storage/Handler/NullSessionHandlerTest.php @@ -28,7 +28,7 @@ class NullSessionHandlerTest extends TestCase { public function testSaveHandlers() { - $storage = $this->getStorage(); + $this->getStorage(); $this->assertEquals('user', ini_get('session.save_handler')); } diff --git a/lib/symfony/http-foundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php b/lib/symfony/http-foundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php index f0914eb43..e710dca92 100644 --- a/lib/symfony/http-foundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php +++ b/lib/symfony/http-foundation/Tests/Session/Storage/Handler/PdoSessionHandlerTest.php @@ -48,22 +48,18 @@ class PdoSessionHandlerTest extends TestCase return $pdo; } - /** - * @expectedException \InvalidArgumentException - */ public function testWrongPdoErrMode() { + $this->expectException('InvalidArgumentException'); $pdo = $this->getMemorySqlitePdo(); $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT); - $storage = new PdoSessionHandler($pdo); + new PdoSessionHandler($pdo); } - /** - * @expectedException \RuntimeException - */ public function testInexistentTable() { + $this->expectException('RuntimeException'); $storage = new PdoSessionHandler($this->getMemorySqlitePdo(), ['db_table' => 'inexistent_table']); $storage->open('', 'sid'); $storage->read('id'); @@ -71,11 +67,9 @@ class PdoSessionHandlerTest extends TestCase $storage->close(); } - /** - * @expectedException \RuntimeException - */ public function testCreateTableTwice() { + $this->expectException('RuntimeException'); $storage = new PdoSessionHandler($this->getMemorySqlitePdo()); $storage->createTable(); } @@ -330,15 +324,15 @@ class PdoSessionHandlerTest extends TestCase public function testUrlDsn($url, $expectedDsn, $expectedUser = null, $expectedPassword = null) { $storage = new PdoSessionHandler($url); + $reflection = new \ReflectionClass(PdoSessionHandler::class); - $this->assertAttributeEquals($expectedDsn, 'dsn', $storage); - - if (null !== $expectedUser) { - $this->assertAttributeEquals($expectedUser, 'username', $storage); - } - - if (null !== $expectedPassword) { - $this->assertAttributeEquals($expectedPassword, 'password', $storage); + foreach (['dsn' => $expectedDsn, 'username' => $expectedUser, 'password' => $expectedPassword] as $property => $expectedValue) { + if (!isset($expectedValue)) { + continue; + } + $property = $reflection->getProperty($property); + $property->setAccessible(true); + $this->assertSame($expectedValue, $property->getValue($storage)); } } diff --git a/lib/symfony/http-foundation/Tests/Session/Storage/MockArraySessionStorageTest.php b/lib/symfony/http-foundation/Tests/Session/Storage/MockArraySessionStorageTest.php index 2e3024ef1..7e0d303b9 100644 --- a/lib/symfony/http-foundation/Tests/Session/Storage/MockArraySessionStorageTest.php +++ b/lib/symfony/http-foundation/Tests/Session/Storage/MockArraySessionStorageTest.php @@ -121,11 +121,9 @@ class MockArraySessionStorageTest extends TestCase $this->assertTrue($storage->isStarted()); } - /** - * @expectedException \RuntimeException - */ public function testUnstartedSave() { + $this->expectException('RuntimeException'); $this->storage->save(); } } diff --git a/lib/symfony/http-foundation/Tests/Session/Storage/MockFileSessionStorageTest.php b/lib/symfony/http-foundation/Tests/Session/Storage/MockFileSessionStorageTest.php index 9e2692dc0..d6bd1823f 100644 --- a/lib/symfony/http-foundation/Tests/Session/Storage/MockFileSessionStorageTest.php +++ b/lib/symfony/http-foundation/Tests/Session/Storage/MockFileSessionStorageTest.php @@ -41,12 +41,12 @@ class MockFileSessionStorageTest extends TestCase protected function tearDown() { - $this->sessionDir = null; - $this->storage = null; - array_map('unlink', glob($this->sessionDir.'/*.session')); + array_map('unlink', glob($this->sessionDir.'/*')); if (is_dir($this->sessionDir)) { rmdir($this->sessionDir); } + $this->sessionDir = null; + $this->storage = null; } public function testStart() @@ -107,11 +107,9 @@ class MockFileSessionStorageTest extends TestCase $this->assertEquals('bar', $storage2->getBag('attributes')->get('foo'), 'values persist between instances'); } - /** - * @expectedException \RuntimeException - */ public function testSaveWithoutStart() { + $this->expectException('RuntimeException'); $storage1 = $this->getStorage(); $storage1->save(); } diff --git a/lib/symfony/http-foundation/Tests/Session/Storage/NativeSessionStorageTest.php b/lib/symfony/http-foundation/Tests/Session/Storage/NativeSessionStorageTest.php index 7cc2eb79c..9ce8108da 100644 --- a/lib/symfony/http-foundation/Tests/Session/Storage/NativeSessionStorageTest.php +++ b/lib/symfony/http-foundation/Tests/Session/Storage/NativeSessionStorageTest.php @@ -72,20 +72,16 @@ class NativeSessionStorageTest extends TestCase $this->assertSame($bag, $storage->getBag($bag->getName())); } - /** - * @expectedException \InvalidArgumentException - */ public function testRegisterBagException() { + $this->expectException('InvalidArgumentException'); $storage = $this->getStorage(); $storage->getBag('non_existing'); } - /** - * @expectedException \LogicException - */ public function testRegisterBagForAStartedSessionThrowsException() { + $this->expectException('LogicException'); $storage = $this->getStorage(); $storage->start(); $storage->registerBag(new AttributeBag()); @@ -98,7 +94,7 @@ class NativeSessionStorageTest extends TestCase $storage->start(); $id = $storage->getId(); - $this->assertInternalType('string', $id); + $this->assertIsString($id); $this->assertNotSame('', $id); $storage->save(); @@ -149,7 +145,7 @@ class NativeSessionStorageTest extends TestCase { $this->iniSet('session.cache_limiter', 'nocache'); - $storage = new NativeSessionStorage(); + new NativeSessionStorage(); $this->assertEquals('', ini_get('session.cache_limiter')); } @@ -157,7 +153,7 @@ class NativeSessionStorageTest extends TestCase { $this->iniSet('session.cache_limiter', 'nocache'); - $storage = new NativeSessionStorage(['cache_limiter' => 'public']); + new NativeSessionStorage(['cache_limiter' => 'public']); $this->assertEquals('public', ini_get('session.cache_limiter')); } @@ -201,11 +197,9 @@ class NativeSessionStorageTest extends TestCase $this->assertSame('200', ini_get('session.cache_expire')); } - /** - * @expectedException \InvalidArgumentException - */ public function testSetSaveHandlerException() { + $this->expectException('InvalidArgumentException'); $storage = $this->getStorage(); $storage->setSaveHandler(new \stdClass()); } @@ -228,11 +222,9 @@ class NativeSessionStorageTest extends TestCase $this->assertInstanceOf('Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy', $storage->getSaveHandler()); } - /** - * @expectedException \RuntimeException - */ public function testStarted() { + $this->expectException('RuntimeException'); $storage = $this->getStorage(); $this->assertFalse($storage->getSaveHandler()->isActive()); diff --git a/lib/symfony/http-foundation/Tests/Session/Storage/Proxy/AbstractProxyTest.php b/lib/symfony/http-foundation/Tests/Session/Storage/Proxy/AbstractProxyTest.php index cbb291f19..ae40f2c29 100644 --- a/lib/symfony/http-foundation/Tests/Session/Storage/Proxy/AbstractProxyTest.php +++ b/lib/symfony/http-foundation/Tests/Session/Storage/Proxy/AbstractProxyTest.php @@ -80,10 +80,10 @@ class AbstractProxyTest extends TestCase /** * @runInSeparateProcess * @preserveGlobalState disabled - * @expectedException \LogicException */ public function testNameException() { + $this->expectException('LogicException'); session_start(); $this->proxy->setName('foo'); } @@ -103,10 +103,10 @@ class AbstractProxyTest extends TestCase /** * @runInSeparateProcess * @preserveGlobalState disabled - * @expectedException \LogicException */ public function testIdException() { + $this->expectException('LogicException'); session_start(); $this->proxy->setId('foo'); } diff --git a/lib/symfony/http-foundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php b/lib/symfony/http-foundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php index b6e0da99d..1457ebd70 100644 --- a/lib/symfony/http-foundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php +++ b/lib/symfony/http-foundation/Tests/Session/Storage/Proxy/SessionHandlerProxyTest.php @@ -25,7 +25,7 @@ use Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy; class SessionHandlerProxyTest extends TestCase { /** - * @var \PHPUnit_Framework_MockObject_Matcher + * @var \PHPUnit\Framework\MockObject\Matcher */ private $mock; @@ -144,7 +144,8 @@ class SessionHandlerProxyTest extends TestCase { $mock = $this->getMockBuilder(['SessionHandlerInterface', 'SessionUpdateTimestampHandlerInterface'])->getMock(); $mock->expects($this->once()) - ->method('updateTimestamp'); + ->method('updateTimestamp') + ->willReturn(false); $proxy = new SessionHandlerProxy($mock); $proxy->updateTimestamp('id', 'data'); diff --git a/lib/symfony/http-foundation/Tests/StreamedResponseTest.php b/lib/symfony/http-foundation/Tests/StreamedResponseTest.php index 62dfc9bc9..a084e917d 100644 --- a/lib/symfony/http-foundation/Tests/StreamedResponseTest.php +++ b/lib/symfony/http-foundation/Tests/StreamedResponseTest.php @@ -81,20 +81,16 @@ class StreamedResponseTest extends TestCase $this->assertEquals(1, $called); } - /** - * @expectedException \LogicException - */ public function testSendContentWithNonCallable() { + $this->expectException('LogicException'); $response = new StreamedResponse(null); $response->sendContent(); } - /** - * @expectedException \LogicException - */ public function testSetContent() { + $this->expectException('LogicException'); $response = new StreamedResponse(function () { echo 'foo'; }); $response->setContent('foo'); } diff --git a/lib/symfony/http-kernel/Bundle/Bundle.php b/lib/symfony/http-kernel/Bundle/Bundle.php index 62b86ca7f..5bbed6bef 100644 --- a/lib/symfony/http-kernel/Bundle/Bundle.php +++ b/lib/symfony/http-kernel/Bundle/Bundle.php @@ -19,8 +19,7 @@ use Symfony\Component\DependencyInjection\Extension\ExtensionInterface; use Symfony\Component\Finder\Finder; /** - * An implementation of BundleInterface that adds a few conventions - * for DependencyInjection extensions and Console commands. + * An implementation of BundleInterface that adds a few conventions for DependencyInjection extensions. * * @author Fabien Potencier */ @@ -88,9 +87,7 @@ abstract class Bundle implements BundleInterface } } - if ($this->extension) { - return $this->extension; - } + return $this->extension ?: null; } /** @@ -200,9 +197,7 @@ abstract class Bundle implements BundleInterface */ protected function createContainerExtension() { - if (class_exists($class = $this->getContainerExtensionClass())) { - return new $class(); - } + return class_exists($class = $this->getContainerExtensionClass()) ? new $class() : null; } private function parseClassName() diff --git a/lib/symfony/http-kernel/Controller/ArgumentResolverInterface.php b/lib/symfony/http-kernel/Controller/ArgumentResolverInterface.php index 5c5123096..ba97775a9 100644 --- a/lib/symfony/http-kernel/Controller/ArgumentResolverInterface.php +++ b/lib/symfony/http-kernel/Controller/ArgumentResolverInterface.php @@ -24,7 +24,6 @@ interface ArgumentResolverInterface /** * Returns the arguments to pass to the controller. * - * @param Request $request * @param callable $controller * * @return array An array of arguments to pass to the controller diff --git a/lib/symfony/http-kernel/Controller/ArgumentValueResolverInterface.php b/lib/symfony/http-kernel/Controller/ArgumentValueResolverInterface.php index fd7b09ecf..6b14ed5be 100644 --- a/lib/symfony/http-kernel/Controller/ArgumentValueResolverInterface.php +++ b/lib/symfony/http-kernel/Controller/ArgumentValueResolverInterface.php @@ -24,9 +24,6 @@ interface ArgumentValueResolverInterface /** * Whether this resolver can resolve the value for the given ArgumentMetadata. * - * @param Request $request - * @param ArgumentMetadata $argument - * * @return bool */ public function supports(Request $request, ArgumentMetadata $argument); @@ -34,9 +31,6 @@ interface ArgumentValueResolverInterface /** * Returns the possible value(s). * - * @param Request $request - * @param ArgumentMetadata $argument - * * @return \Generator */ public function resolve(Request $request, ArgumentMetadata $argument); diff --git a/lib/symfony/http-kernel/Controller/ControllerResolver.php b/lib/symfony/http-kernel/Controller/ControllerResolver.php index e657f6143..c981642fe 100644 --- a/lib/symfony/http-kernel/Controller/ControllerResolver.php +++ b/lib/symfony/http-kernel/Controller/ControllerResolver.php @@ -85,10 +85,10 @@ class ControllerResolver implements ArgumentResolverInterface, ControllerResolve } } - $callable = $this->createController($controller); - - if (!\is_callable($callable)) { - throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable. %s', $request->getPathInfo(), $this->getControllerError($callable))); + try { + $callable = $this->createController($controller); + } catch (\InvalidArgumentException $e) { + throw new \InvalidArgumentException(sprintf('The controller for URI "%s" is not callable. %s', $request->getPathInfo(), $e->getMessage())); } return $callable; @@ -116,7 +116,6 @@ class ControllerResolver implements ArgumentResolverInterface, ControllerResolve } /** - * @param Request $request * @param callable $controller * @param \ReflectionParameter[] $parameters * @@ -166,7 +165,7 @@ class ControllerResolver implements ArgumentResolverInterface, ControllerResolve * * @return callable A PHP callable * - * @throws \InvalidArgumentException + * @throws \InvalidArgumentException When the controller cannot be created */ protected function createController($controller) { @@ -180,7 +179,13 @@ class ControllerResolver implements ArgumentResolverInterface, ControllerResolve throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class)); } - return [$this->instantiateController($class), $method]; + $controller = [$this->instantiateController($class), $method]; + + if (!\is_callable($controller)) { + throw new \InvalidArgumentException($this->getControllerError($controller)); + } + + return $controller; } /** diff --git a/lib/symfony/http-kernel/ControllerMetadata/ArgumentMetadata.php b/lib/symfony/http-kernel/ControllerMetadata/ArgumentMetadata.php index 32316a8d5..520e83b5f 100644 --- a/lib/symfony/http-kernel/ControllerMetadata/ArgumentMetadata.php +++ b/lib/symfony/http-kernel/ControllerMetadata/ArgumentMetadata.php @@ -58,7 +58,7 @@ class ArgumentMetadata * * The type is the PHP class in 5.5+ and additionally the basic type in PHP 7.0+. * - * @return string + * @return string|null */ public function getType() { diff --git a/lib/symfony/http-kernel/ControllerMetadata/ArgumentMetadataFactory.php b/lib/symfony/http-kernel/ControllerMetadata/ArgumentMetadataFactory.php index fa48d0cc1..2548a2a08 100644 --- a/lib/symfony/http-kernel/ControllerMetadata/ArgumentMetadataFactory.php +++ b/lib/symfony/http-kernel/ControllerMetadata/ArgumentMetadataFactory.php @@ -67,8 +67,6 @@ final class ArgumentMetadataFactory implements ArgumentMetadataFactoryInterface /** * Returns whether an argument is variadic. * - * @param \ReflectionParameter $parameter - * * @return bool */ private function isVariadic(\ReflectionParameter $parameter) @@ -79,8 +77,6 @@ final class ArgumentMetadataFactory implements ArgumentMetadataFactoryInterface /** * Determines whether an argument has a default value. * - * @param \ReflectionParameter $parameter - * * @return bool */ private function hasDefaultValue(\ReflectionParameter $parameter) @@ -91,8 +87,6 @@ final class ArgumentMetadataFactory implements ArgumentMetadataFactoryInterface /** * Returns a default value if available. * - * @param \ReflectionParameter $parameter - * * @return mixed|null */ private function getDefaultValue(\ReflectionParameter $parameter) @@ -103,25 +97,23 @@ final class ArgumentMetadataFactory implements ArgumentMetadataFactoryInterface /** * Returns an associated type to the given parameter if available. * - * @param \ReflectionParameter $parameter - * * @return string|null */ private function getType(\ReflectionParameter $parameter, \ReflectionFunctionAbstract $function) { if ($this->supportsParameterType) { if (!$type = $parameter->getType()) { - return; + return null; } $name = $type instanceof \ReflectionNamedType ? $type->getName() : $type->__toString(); if ('array' === $name && !$type->isBuiltin()) { // Special case for HHVM with variadics - return; + return null; } } elseif (preg_match('/^(?:[^ ]++ ){4}([a-zA-Z_\x7F-\xFF][^ ]++)/', $parameter, $name)) { $name = $name[1]; } else { - return; + return null; } $lcName = strtolower($name); @@ -129,7 +121,7 @@ final class ArgumentMetadataFactory implements ArgumentMetadataFactoryInterface return $name; } if (!$function instanceof \ReflectionMethod) { - return; + return null; } if ('self' === $lcName) { return $function->getDeclaringClass()->name; @@ -137,5 +129,7 @@ final class ArgumentMetadataFactory implements ArgumentMetadataFactoryInterface if ($parent = $function->getDeclaringClass()->getParentClass()) { return $parent->name; } + + return null; } } diff --git a/lib/symfony/http-kernel/DataCollector/ConfigDataCollector.php b/lib/symfony/http-kernel/DataCollector/ConfigDataCollector.php index 626c1cc69..673bf5c5f 100644 --- a/lib/symfony/http-kernel/DataCollector/ConfigDataCollector.php +++ b/lib/symfony/http-kernel/DataCollector/ConfigDataCollector.php @@ -81,8 +81,8 @@ class ConfigDataCollector extends DataCollector implements LateDataCollectorInte $this->data['symfony_state'] = $this->determineSymfonyState(); $this->data['symfony_minor_version'] = sprintf('%s.%s', Kernel::MAJOR_VERSION, Kernel::MINOR_VERSION); - $eom = \DateTime::createFromFormat('m/Y', Kernel::END_OF_MAINTENANCE); - $eol = \DateTime::createFromFormat('m/Y', Kernel::END_OF_LIFE); + $eom = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE); + $eol = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE); $this->data['symfony_eom'] = $eom->format('F Y'); $this->data['symfony_eol'] = $eol->format('F Y'); } @@ -119,7 +119,7 @@ class ConfigDataCollector extends DataCollector implements LateDataCollectorInte /** * Gets the token. * - * @return string The token + * @return string|null The token */ public function getToken() { @@ -314,8 +314,8 @@ class ConfigDataCollector extends DataCollector implements LateDataCollectorInte private function determineSymfonyState() { $now = new \DateTime(); - $eom = \DateTime::createFromFormat('m/Y', Kernel::END_OF_MAINTENANCE)->modify('last day of this month'); - $eol = \DateTime::createFromFormat('m/Y', Kernel::END_OF_LIFE)->modify('last day of this month'); + $eom = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_MAINTENANCE)->modify('last day of this month'); + $eol = \DateTime::createFromFormat('d/m/Y', '01/'.Kernel::END_OF_LIFE)->modify('last day of this month'); if ($now > $eol) { $versionState = 'eol'; diff --git a/lib/symfony/http-kernel/DataCollector/DataCollector.php b/lib/symfony/http-kernel/DataCollector/DataCollector.php index 4346e0ec0..94307cf56 100644 --- a/lib/symfony/http-kernel/DataCollector/DataCollector.php +++ b/lib/symfony/http-kernel/DataCollector/DataCollector.php @@ -28,6 +28,9 @@ use Symfony\Component\VarDumper\Cloner\VarCloner; */ abstract class DataCollector implements DataCollectorInterface, \Serializable { + /** + * @var array|Data + */ protected $data = []; /** diff --git a/lib/symfony/http-kernel/DataCollector/ExceptionDataCollector.php b/lib/symfony/http-kernel/DataCollector/ExceptionDataCollector.php index c76e7f45b..f9be5bddf 100644 --- a/lib/symfony/http-kernel/DataCollector/ExceptionDataCollector.php +++ b/lib/symfony/http-kernel/DataCollector/ExceptionDataCollector.php @@ -55,7 +55,7 @@ class ExceptionDataCollector extends DataCollector /** * Gets the exception. * - * @return \Exception The exception + * @return \Exception|FlattenException */ public function getException() { diff --git a/lib/symfony/http-kernel/DataCollector/LoggerDataCollector.php b/lib/symfony/http-kernel/DataCollector/LoggerDataCollector.php index a8dda9f67..99a9cf23e 100644 --- a/lib/symfony/http-kernel/DataCollector/LoggerDataCollector.php +++ b/lib/symfony/http-kernel/DataCollector/LoggerDataCollector.php @@ -72,11 +72,6 @@ class LoggerDataCollector extends DataCollector implements LateDataCollectorInte } } - /** - * Gets the logs. - * - * @return array An array of logs - */ public function getLogs() { return isset($this->data['logs']) ? $this->data['logs'] : []; diff --git a/lib/symfony/http-kernel/DataCollector/RequestDataCollector.php b/lib/symfony/http-kernel/DataCollector/RequestDataCollector.php index 671865aa1..246c0c7f6 100644 --- a/lib/symfony/http-kernel/DataCollector/RequestDataCollector.php +++ b/lib/symfony/http-kernel/DataCollector/RequestDataCollector.php @@ -49,7 +49,6 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter } } - $content = null; try { $content = $request->getContent(); } catch (\LogicException $e) { @@ -59,7 +58,6 @@ class RequestDataCollector extends DataCollector implements EventSubscriberInter $sessionMetadata = []; $sessionAttributes = []; - $session = null; $flashes = []; if ($request->hasSession()) { $session = $request->getSession(); diff --git a/lib/symfony/http-kernel/DataCollector/TimeDataCollector.php b/lib/symfony/http-kernel/DataCollector/TimeDataCollector.php index 7ab14b7cb..cb490c2bb 100644 --- a/lib/symfony/http-kernel/DataCollector/TimeDataCollector.php +++ b/lib/symfony/http-kernel/DataCollector/TimeDataCollector.php @@ -15,10 +15,9 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\KernelInterface; use Symfony\Component\Stopwatch\Stopwatch; +use Symfony\Component\Stopwatch\StopwatchEvent; /** - * TimeDataCollector. - * * @author Fabien Potencier */ class TimeDataCollector extends DataCollector implements LateDataCollectorInterface @@ -77,7 +76,7 @@ class TimeDataCollector extends DataCollector implements LateDataCollectorInterf /** * Sets the request events. * - * @param array $events The request events + * @param StopwatchEvent[] $events The request events */ public function setEvents(array $events) { @@ -91,7 +90,7 @@ class TimeDataCollector extends DataCollector implements LateDataCollectorInterf /** * Gets the request events. * - * @return array The request events + * @return StopwatchEvent[] The request events */ public function getEvents() { @@ -133,7 +132,7 @@ class TimeDataCollector extends DataCollector implements LateDataCollectorInterf /** * Gets the request time. * - * @return int The time + * @return float */ public function getStartTime() { diff --git a/lib/symfony/http-kernel/Debug/FileLinkFormatter.php b/lib/symfony/http-kernel/Debug/FileLinkFormatter.php index af65f7ec5..e7347d490 100644 --- a/lib/symfony/http-kernel/Debug/FileLinkFormatter.php +++ b/lib/symfony/http-kernel/Debug/FileLinkFormatter.php @@ -102,14 +102,16 @@ class FileLinkFormatter implements \Serializable $request = $this->requestStack->getMasterRequest(); if ($request instanceof Request) { if ($this->urlFormat instanceof \Closure && !$this->urlFormat = \call_user_func($this->urlFormat)) { - return; + return null; } return [ - $request->getSchemeAndHttpHost().$request->getBasePath().$this->urlFormat, + $request->getSchemeAndHttpHost().$this->urlFormat, $this->baseDir.\DIRECTORY_SEPARATOR, '', ]; } } + + return null; } } diff --git a/lib/symfony/http-kernel/Debug/TraceableEventDispatcher.php b/lib/symfony/http-kernel/Debug/TraceableEventDispatcher.php index ddf4fa7ce..c265b6010 100644 --- a/lib/symfony/http-kernel/Debug/TraceableEventDispatcher.php +++ b/lib/symfony/http-kernel/Debug/TraceableEventDispatcher.php @@ -42,6 +42,9 @@ class TraceableEventDispatcher extends BaseTraceableEventDispatcher break; case KernelEvents::TERMINATE: $token = $event->getResponse()->headers->get('X-Debug-Token'); + if (null === $token) { + break; + } // There is a very special case when using built-in AppCache class as kernel wrapper, in the case // of an ESI request leading to a `stale` response [B] inside a `fresh` cached response [A]. // In this case, `$token` contains the [B] debug token, but the open `stopwatch` section ID @@ -66,12 +69,18 @@ class TraceableEventDispatcher extends BaseTraceableEventDispatcher break; case KernelEvents::RESPONSE: $token = $event->getResponse()->headers->get('X-Debug-Token'); + if (null === $token) { + break; + } $this->stopwatch->stopSection($token); break; case KernelEvents::TERMINATE: // In the special case described in the `preDispatch` method above, the `$token` section // does not exist, then closing it throws an exception which must be caught. $token = $event->getResponse()->headers->get('X-Debug-Token'); + if (null === $token) { + break; + } try { $this->stopwatch->stopSection($token); } catch (\LogicException $e) { diff --git a/lib/symfony/http-kernel/EventListener/AbstractSessionListener.php b/lib/symfony/http-kernel/EventListener/AbstractSessionListener.php index aee5d6f88..0a6bb4f79 100644 --- a/lib/symfony/http-kernel/EventListener/AbstractSessionListener.php +++ b/lib/symfony/http-kernel/EventListener/AbstractSessionListener.php @@ -56,6 +56,7 @@ abstract class AbstractSessionListener implements EventSubscriberInterface if ($session instanceof Session ? $session->getUsageIndex() !== end($this->sessionUsageStack) : $session->isStarted()) { $event->getResponse() + ->setExpires(new \DateTime()) ->setPrivate() ->setMaxAge(0) ->headers->addCacheControlDirective('must-revalidate'); diff --git a/lib/symfony/http-kernel/EventListener/RouterListener.php b/lib/symfony/http-kernel/EventListener/RouterListener.php index 378327b57..3803105e8 100644 --- a/lib/symfony/http-kernel/EventListener/RouterListener.php +++ b/lib/symfony/http-kernel/EventListener/RouterListener.php @@ -89,8 +89,6 @@ class RouterListener implements EventSubscriberInterface /** * After a sub-request is done, we need to reset the routing context to the parent request so that the URL generator * operates on the correct context again. - * - * @param FinishRequestEvent $event */ public function onKernelFinishRequest(FinishRequestEvent $event) { diff --git a/lib/symfony/http-kernel/EventListener/SaveSessionListener.php b/lib/symfony/http-kernel/EventListener/SaveSessionListener.php index 5901200a7..5f5cd2480 100644 --- a/lib/symfony/http-kernel/EventListener/SaveSessionListener.php +++ b/lib/symfony/http-kernel/EventListener/SaveSessionListener.php @@ -29,7 +29,7 @@ use Symfony\Component\HttpKernel\KernelEvents; * the one above. But by saving the session before long-running things in the terminate event, * we ensure the session is not blocked longer than needed. * * When regenerating the session ID no locking is involved in PHPs session design. See - * https://bugs.php.net/bug.php?id=61470 for a discussion. So in this case, the session must + * https://bugs.php.net/61470 for a discussion. So in this case, the session must * be saved anyway before sending the headers with the new session ID. Otherwise session * data could get lost again for concurrent requests with the new ID. One result could be * that you get logged out after just logging in. diff --git a/lib/symfony/http-kernel/EventListener/SessionListener.php b/lib/symfony/http-kernel/EventListener/SessionListener.php index 39ebfd922..9e36b7626 100644 --- a/lib/symfony/http-kernel/EventListener/SessionListener.php +++ b/lib/symfony/http-kernel/EventListener/SessionListener.php @@ -32,7 +32,7 @@ class SessionListener extends AbstractSessionListener protected function getSession() { if (!$this->container->has('session')) { - return; + return null; } return $this->container->get('session'); diff --git a/lib/symfony/http-kernel/EventListener/TestSessionListener.php b/lib/symfony/http-kernel/EventListener/TestSessionListener.php index 36abb422f..e2c6f5c9e 100644 --- a/lib/symfony/http-kernel/EventListener/TestSessionListener.php +++ b/lib/symfony/http-kernel/EventListener/TestSessionListener.php @@ -32,7 +32,7 @@ class TestSessionListener extends AbstractTestSessionListener protected function getSession() { if (!$this->container->has('session')) { - return; + return null; } return $this->container->get('session'); diff --git a/lib/symfony/http-kernel/Fragment/FragmentHandler.php b/lib/symfony/http-kernel/Fragment/FragmentHandler.php index f40da0018..9629cf706 100644 --- a/lib/symfony/http-kernel/Fragment/FragmentHandler.php +++ b/lib/symfony/http-kernel/Fragment/FragmentHandler.php @@ -108,5 +108,7 @@ class FragmentHandler } $response->sendContent(); + + return null; } } diff --git a/lib/symfony/http-kernel/Fragment/HIncludeFragmentRenderer.php b/lib/symfony/http-kernel/Fragment/HIncludeFragmentRenderer.php index a0abc0588..f94a5c076 100644 --- a/lib/symfony/http-kernel/Fragment/HIncludeFragmentRenderer.php +++ b/lib/symfony/http-kernel/Fragment/HIncludeFragmentRenderer.php @@ -19,6 +19,7 @@ use Symfony\Component\Templating\EngineInterface; use Twig\Environment; use Twig\Error\LoaderError; use Twig\Loader\ExistsLoaderInterface; +use Twig\Loader\SourceContextLoaderInterface; /** * Implements the Hinclude rendering strategy. @@ -137,22 +138,23 @@ class HIncludeFragmentRenderer extends RoutableFragmentRenderer } $loader = $this->templating->getLoader(); - if ($loader instanceof ExistsLoaderInterface || method_exists($loader, 'exists')) { - return $loader->exists($template); - } - try { - if (method_exists($loader, 'getSourceContext')) { - $loader->getSourceContext($template); - } else { - $loader->getSource($template); + if (1 === Environment::MAJOR_VERSION && !$loader instanceof ExistsLoaderInterface) { + try { + if ($loader instanceof SourceContextLoaderInterface) { + $loader->getSourceContext($template); + } else { + $loader->getSource($template); + } + + return true; + } catch (LoaderError $e) { } - return true; - } catch (LoaderError $e) { + return false; } - return false; + return $loader->exists($template); } /** diff --git a/lib/symfony/http-kernel/HttpCache/AbstractSurrogate.php b/lib/symfony/http-kernel/HttpCache/AbstractSurrogate.php index 8918a3057..9b4541793 100644 --- a/lib/symfony/http-kernel/HttpCache/AbstractSurrogate.php +++ b/lib/symfony/http-kernel/HttpCache/AbstractSurrogate.php @@ -109,6 +109,8 @@ abstract class AbstractSurrogate implements SurrogateInterface throw $e; } } + + return ''; } /** diff --git a/lib/symfony/http-kernel/HttpCache/Esi.php b/lib/symfony/http-kernel/HttpCache/Esi.php index dc62990b4..96e6ca4bf 100644 --- a/lib/symfony/http-kernel/HttpCache/Esi.php +++ b/lib/symfony/http-kernel/HttpCache/Esi.php @@ -111,5 +111,7 @@ class Esi extends AbstractSurrogate // remove ESI/1.0 from the Surrogate-Control header $this->removeFromControl($response); + + return $response; } } diff --git a/lib/symfony/http-kernel/HttpCache/HttpCache.php b/lib/symfony/http-kernel/HttpCache/HttpCache.php index daaa928fa..addeca8ba 100644 --- a/lib/symfony/http-kernel/HttpCache/HttpCache.php +++ b/lib/symfony/http-kernel/HttpCache/HttpCache.php @@ -432,9 +432,8 @@ class HttpCache implements HttpKernelInterface, TerminableInterface * All backend requests (cache passes, fetches, cache validations) * run through this method. * - * @param Request $request A Request instance - * @param bool $catch Whether to catch exceptions or not - * @param Response $entry A Response instance (the stale entry if present, null otherwise) + * @param bool $catch Whether to catch exceptions or not + * @param Response|null $entry A Response instance (the stale entry if present, null otherwise) * * @return Response A Response instance */ @@ -646,8 +645,6 @@ class HttpCache implements HttpKernelInterface, TerminableInterface /** * Calculates the key we use in the "trace" array for a given request. * - * @param Request $request - * * @return string */ private function getTraceKey(Request $request) @@ -664,8 +661,6 @@ class HttpCache implements HttpKernelInterface, TerminableInterface * Checks whether the given (cached) response may be served as "stale" when a revalidation * is currently in progress. * - * @param Response $entry - * * @return bool true when the stale response may be served, false otherwise */ private function mayServeStaleWhileRevalidate(Response $entry) diff --git a/lib/symfony/http-kernel/HttpCache/ResponseCacheStrategy.php b/lib/symfony/http-kernel/HttpCache/ResponseCacheStrategy.php index 25c071c33..3bdf0f519 100644 --- a/lib/symfony/http-kernel/HttpCache/ResponseCacheStrategy.php +++ b/lib/symfony/http-kernel/HttpCache/ResponseCacheStrategy.php @@ -130,7 +130,6 @@ class ResponseCacheStrategy implements ResponseCacheStrategyInterface $response->headers->set('Cache-Control', implode(', ', array_keys($flags))); $maxAge = null; - $sMaxage = null; if (is_numeric($this->ageDirectives['max-age'])) { $maxAge = $this->ageDirectives['max-age'] + $this->age; diff --git a/lib/symfony/http-kernel/HttpCache/Ssi.php b/lib/symfony/http-kernel/HttpCache/Ssi.php index eaaa230b5..40aac64f2 100644 --- a/lib/symfony/http-kernel/HttpCache/Ssi.php +++ b/lib/symfony/http-kernel/HttpCache/Ssi.php @@ -94,5 +94,7 @@ class Ssi extends AbstractSurrogate // remove SSI/1.0 from the Surrogate-Control header $this->removeFromControl($response); + + return $response; } } diff --git a/lib/symfony/http-kernel/HttpCache/Store.php b/lib/symfony/http-kernel/HttpCache/Store.php index ffd4f01ae..c831ba2ac 100644 --- a/lib/symfony/http-kernel/HttpCache/Store.php +++ b/lib/symfony/http-kernel/HttpCache/Store.php @@ -134,7 +134,7 @@ class Store implements StoreInterface $key = $this->getCacheKey($request); if (!$entries = $this->getMetadata($key)) { - return; + return null; } // find a cached entry that matches the request. @@ -148,7 +148,7 @@ class Store implements StoreInterface } if (null === $match) { - return; + return null; } $headers = $match[1]; @@ -159,6 +159,7 @@ class Store implements StoreInterface // TODO the metaStore referenced an entity that doesn't exist in // the entityStore. We definitely want to return nil but we should // also purge the entry from the meta-store when this is detected. + return null; } /** @@ -180,7 +181,7 @@ class Store implements StoreInterface if (!$response->headers->has('X-Content-Digest')) { $digest = $this->generateContentDigest($response); - if (false === $this->save($digest, $response->getContent())) { + if (!$this->save($digest, $response->getContent())) { throw new \RuntimeException('Unable to store the entity.'); } @@ -209,7 +210,7 @@ class Store implements StoreInterface array_unshift($entries, [$storedEnv, $headers]); - if (false === $this->save($key, serialize($entries))) { + if (!$this->save($key, serialize($entries))) { throw new \RuntimeException('Unable to store the metadata.'); } @@ -248,7 +249,7 @@ class Store implements StoreInterface } } - if ($modified && false === $this->save($key, serialize($entries))) { + if ($modified && !$this->save($key, serialize($entries))) { throw new \RuntimeException('Unable to store the metadata.'); } } @@ -349,13 +350,13 @@ class Store implements StoreInterface * * @param string $key The store key * - * @return string The data associated with the key + * @return string|null The data associated with the key */ private function load($key) { $path = $this->getPath($key); - return file_exists($path) ? file_get_contents($path) : false; + return file_exists($path) && false !== ($contents = file_get_contents($path)) ? $contents : null; } /** @@ -408,6 +409,8 @@ class Store implements StoreInterface } @chmod($path, 0666 & ~umask()); + + return true; } public function getPath($key) diff --git a/lib/symfony/http-kernel/HttpKernel.php b/lib/symfony/http-kernel/HttpKernel.php index 1e19923eb..bca2cd168 100644 --- a/lib/symfony/http-kernel/HttpKernel.php +++ b/lib/symfony/http-kernel/HttpKernel.php @@ -202,8 +202,7 @@ class HttpKernel implements HttpKernelInterface, TerminableInterface * operations such as {@link RequestStack::getParentRequest()} can lead to * weird results. * - * @param Request $request - * @param int $type + * @param int $type */ private function finishRequest(Request $request, $type) { diff --git a/lib/symfony/http-kernel/Kernel.php b/lib/symfony/http-kernel/Kernel.php index 90ef0c537..05b11f366 100644 --- a/lib/symfony/http-kernel/Kernel.php +++ b/lib/symfony/http-kernel/Kernel.php @@ -67,11 +67,11 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl private $requestStackSize = 0; private $resetServices = false; - const VERSION = '3.4.30'; - const VERSION_ID = 30430; + const VERSION = '3.4.35'; + const VERSION_ID = 30435; const MAJOR_VERSION = 3; const MINOR_VERSION = 4; - const RELEASE_VERSION = 30; + const RELEASE_VERSION = 35; const EXTRA_VERSION = ''; const END_OF_MAINTENANCE = '11/2020'; @@ -206,7 +206,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl /** * Gets a HTTP kernel from the container. * - * @return HttpKernel + * @return HttpKernelInterface */ protected function getHttpKernel() { @@ -354,7 +354,12 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl { if (null === $this->projectDir) { $r = new \ReflectionObject($this); - $dir = $rootDir = \dirname($r->getFileName()); + + if (!file_exists($dir = $r->getFileName())) { + throw new \LogicException(sprintf('Cannot auto-detect project dir for kernel of class "%s".', $r->name)); + } + + $dir = $rootDir = \dirname($dir); while (!file_exists($dir.'/composer.json')) { if ($dir === \dirname($dir)) { return $this->projectDir = $rootDir; @@ -425,7 +430,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl */ public function getStartTime() { - return $this->debug ? $this->startTime : -INF; + return $this->debug && null !== $this->startTime ? $this->startTime : -INF; } /** @@ -597,10 +602,9 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl return; } - if ($this->debug) { + if ($collectDeprecations = $this->debug && !\defined('PHPUNIT_COMPOSER_INSTALL')) { $collectedLogs = []; - $previousHandler = \defined('PHPUNIT_COMPOSER_INSTALL'); - $previousHandler = $previousHandler ?: set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) { + $previousHandler = set_error_handler(function ($type, $message, $file, $line) use (&$collectedLogs, &$previousHandler) { if (E_USER_DEPRECATED !== $type && E_DEPRECATED !== $type) { return $previousHandler ? $previousHandler($type, $message, $file, $line) : false; } @@ -608,7 +612,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl if (isset($collectedLogs[$message])) { ++$collectedLogs[$message]['count']; - return; + return null; } $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3); @@ -628,6 +632,8 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl 'trace' => $backtrace, 'count' => 1, ]; + + return null; }); } @@ -636,7 +642,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl $container = $this->buildContainer(); $container->compile(); } finally { - if ($this->debug && true !== $previousHandler) { + if ($collectDeprecations) { restore_error_handler(); file_put_contents($cacheDir.'/'.$class.'Deprecations.log', serialize(array_values($collectedLogs))); @@ -667,7 +673,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl static $legacyContainers = []; $oldContainerDir = \dirname($oldContainer->getFileName()); $legacyContainers[$oldContainerDir.'.legacy'] = true; - foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy') as $legacyContainer) { + foreach (glob(\dirname($oldContainerDir).\DIRECTORY_SEPARATOR.'*.legacy', GLOB_NOSORT) as $legacyContainer) { if (!isset($legacyContainers[$legacyContainer]) && @unlink($legacyContainer)) { (new Filesystem())->remove(substr($legacyContainer, 0, -7)); } @@ -862,7 +868,7 @@ abstract class Kernel implements KernelInterface, RebootableInterface, Terminabl $fs->dumpFile($dir.$file, $code); @chmod($dir.$file, 0666 & ~umask()); } - $legacyFile = \dirname($dir.$file).'.legacy'; + $legacyFile = \dirname($dir.key($content)).'.legacy'; if (file_exists($legacyFile)) { @unlink($legacyFile); } diff --git a/lib/symfony/http-kernel/KernelInterface.php b/lib/symfony/http-kernel/KernelInterface.php index d624d1219..2445bbb43 100644 --- a/lib/symfony/http-kernel/KernelInterface.php +++ b/lib/symfony/http-kernel/KernelInterface.php @@ -138,7 +138,7 @@ interface KernelInterface extends HttpKernelInterface, \Serializable /** * Gets the request start time (not available if debug is disabled). * - * @return int The request start timestamp + * @return float The request start timestamp */ public function getStartTime(); diff --git a/lib/symfony/http-kernel/Log/Logger.php b/lib/symfony/http-kernel/Log/Logger.php index e174587d1..50cbcd428 100644 --- a/lib/symfony/http-kernel/Log/Logger.php +++ b/lib/symfony/http-kernel/Log/Logger.php @@ -83,7 +83,6 @@ class Logger extends AbstractLogger /** * @param string $level * @param string $message - * @param array $context * * @return string */ diff --git a/lib/symfony/http-kernel/Profiler/FileProfilerStorage.php b/lib/symfony/http-kernel/Profiler/FileProfilerStorage.php index 810e2fe6f..8589b96f5 100644 --- a/lib/symfony/http-kernel/Profiler/FileProfilerStorage.php +++ b/lib/symfony/http-kernel/Profiler/FileProfilerStorage.php @@ -118,7 +118,7 @@ class FileProfilerStorage implements ProfilerStorageInterface public function read($token) { if (!$token || !file_exists($file = $this->getFilename($token))) { - return; + return null; } return $this->createProfileFromData($token, unserialize(file_get_contents($file))); @@ -229,7 +229,7 @@ class FileProfilerStorage implements ProfilerStorageInterface $position = ftell($file); if (0 === $position) { - return; + return null; } while (true) { diff --git a/lib/symfony/http-kernel/Profiler/Profile.php b/lib/symfony/http-kernel/Profiler/Profile.php index c4490bc7a..3665545d2 100644 --- a/lib/symfony/http-kernel/Profiler/Profile.php +++ b/lib/symfony/http-kernel/Profiler/Profile.php @@ -102,7 +102,7 @@ class Profile /** * Returns the IP. * - * @return string The IP + * @return string|null The IP */ public function getIp() { @@ -122,7 +122,7 @@ class Profile /** * Returns the request method. * - * @return string The request method + * @return string|null The request method */ public function getMethod() { @@ -137,13 +137,16 @@ class Profile /** * Returns the URL. * - * @return string The URL + * @return string|null The URL */ public function getUrl() { return $this->url; } + /** + * @param string $url + */ public function setUrl($url) { $this->url = $url; @@ -180,7 +183,7 @@ class Profile } /** - * @return int + * @return int|null */ public function getStatusCode() { diff --git a/lib/symfony/http-kernel/Profiler/Profiler.php b/lib/symfony/http-kernel/Profiler/Profiler.php index edf6cb833..c510afa3e 100644 --- a/lib/symfony/http-kernel/Profiler/Profiler.php +++ b/lib/symfony/http-kernel/Profiler/Profiler.php @@ -65,12 +65,12 @@ class Profiler /** * Loads the Profile for the given Response. * - * @return Profile|false A Profile instance + * @return Profile|null A Profile instance */ public function loadProfileFromResponse(Response $response) { if (!$token = $response->headers->get('X-Debug-Token')) { - return false; + return null; } return $this->loadProfile($token); @@ -81,7 +81,7 @@ class Profiler * * @param string $token A token * - * @return Profile A Profile instance + * @return Profile|null A Profile instance */ public function loadProfile($token) { @@ -130,7 +130,7 @@ class Profiler * * @return array An array of tokens * - * @see http://php.net/manual/en/datetime.formats.php for the supported date/time formats + * @see https://php.net/datetime.formats for the supported date/time formats */ public function find($ip, $url, $limit, $method, $start, $end, $statusCode = null) { @@ -145,7 +145,7 @@ class Profiler public function collect(Request $request, Response $response, \Exception $exception = null) { if (false === $this->enabled) { - return; + return null; } $profile = new Profile(substr(hash('sha256', uniqid(mt_rand(), true)), 0, 6)); @@ -248,16 +248,19 @@ class Profiler return $this->collectors[$name]; } + /** + * @return int|null + */ private function getTimestamp($value) { if (null === $value || '' == $value) { - return; + return null; } try { $value = new \DateTime(is_numeric($value) ? '@'.$value : $value); } catch (\Exception $e) { - return; + return null; } return $value->getTimestamp(); diff --git a/lib/symfony/http-kernel/Profiler/ProfilerStorageInterface.php b/lib/symfony/http-kernel/Profiler/ProfilerStorageInterface.php index 544fb1fef..04cba51e2 100644 --- a/lib/symfony/http-kernel/Profiler/ProfilerStorageInterface.php +++ b/lib/symfony/http-kernel/Profiler/ProfilerStorageInterface.php @@ -39,7 +39,7 @@ interface ProfilerStorageInterface * * @param string $token A token * - * @return Profile The profile associated with token + * @return Profile|null The profile associated with token */ public function read($token); diff --git a/lib/symfony/http-kernel/Tests/Bundle/BundleTest.php b/lib/symfony/http-kernel/Tests/Bundle/BundleTest.php index 3408d7acd..6803579c6 100644 --- a/lib/symfony/http-kernel/Tests/Bundle/BundleTest.php +++ b/lib/symfony/http-kernel/Tests/Bundle/BundleTest.php @@ -50,11 +50,12 @@ class BundleTest extends TestCase } /** - * @expectedException \LogicException - * @expectedExceptionMessage must implement Symfony\Component\DependencyInjection\Extension\ExtensionInterface + * @group legacy */ public function testGetContainerExtensionWithInvalidClass() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('must implement Symfony\Component\DependencyInjection\Extension\ExtensionInterface'); $bundle = new ExtensionNotValidBundle(); $bundle->getContainerExtension(); } diff --git a/lib/symfony/http-kernel/Tests/CacheClearer/Psr6CacheClearerTest.php b/lib/symfony/http-kernel/Tests/CacheClearer/Psr6CacheClearerTest.php index 297ede6a3..2fbce41d1 100644 --- a/lib/symfony/http-kernel/Tests/CacheClearer/Psr6CacheClearerTest.php +++ b/lib/symfony/http-kernel/Tests/CacheClearer/Psr6CacheClearerTest.php @@ -37,12 +37,10 @@ class Psr6CacheClearerTest extends TestCase (new Psr6CacheClearer(['pool' => $pool]))->clearPool('pool'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Cache pool not found: unknown - */ public function testClearPoolThrowsExceptionOnUnreferencedPool() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Cache pool not found: unknown'); (new Psr6CacheClearer())->clearPool('unknown'); } diff --git a/lib/symfony/http-kernel/Tests/CacheWarmer/CacheWarmerTest.php b/lib/symfony/http-kernel/Tests/CacheWarmer/CacheWarmerTest.php index 4d34e7bfc..400e48457 100644 --- a/lib/symfony/http-kernel/Tests/CacheWarmer/CacheWarmerTest.php +++ b/lib/symfony/http-kernel/Tests/CacheWarmer/CacheWarmerTest.php @@ -36,11 +36,9 @@ class CacheWarmerTest extends TestCase $this->assertFileExists(self::$cacheFile); } - /** - * @expectedException \RuntimeException - */ public function testWriteNonWritableCacheFileThrowsARuntimeException() { + $this->expectException('RuntimeException'); $nonWritableFile = '/this/file/is/very/probably/not/writable'; $warmer = new TestCacheWarmer($nonWritableFile); $warmer->warmUp(\dirname($nonWritableFile)); diff --git a/lib/symfony/http-kernel/Tests/ClientTest.php b/lib/symfony/http-kernel/Tests/ClientTest.php index 86a51ce76..b141c16d6 100644 --- a/lib/symfony/http-kernel/Tests/ClientTest.php +++ b/lib/symfony/http-kernel/Tests/ClientTest.php @@ -39,8 +39,8 @@ class ClientTest extends TestCase $this->assertEquals('Request: /', $client->getResponse()->getContent(), '->doRequest() uses the request handler to make the request'); $this->assertEquals('www.example.com', $client->getRequest()->getHost(), '->doRequest() uses the request handler to make the request'); - $client->request('GET', 'http://www.example.com/?parameter=http://google.com'); - $this->assertEquals('http://www.example.com/?parameter='.urlencode('http://google.com'), $client->getRequest()->getUri(), '->doRequest() uses the request handler to make the request'); + $client->request('GET', 'http://www.example.com/?parameter=http://example.com'); + $this->assertEquals('http://www.example.com/?parameter='.urlencode('http://example.com'), $client->getRequest()->getUri(), '->doRequest() uses the request handler to make the request'); } public function testGetScript() diff --git a/lib/symfony/http-kernel/Tests/Config/FileLocatorTest.php b/lib/symfony/http-kernel/Tests/Config/FileLocatorTest.php index b20b12ab5..72b38c672 100644 --- a/lib/symfony/http-kernel/Tests/Config/FileLocatorTest.php +++ b/lib/symfony/http-kernel/Tests/Config/FileLocatorTest.php @@ -30,7 +30,7 @@ class FileLocatorTest extends TestCase $kernel ->expects($this->never()) ->method('locateResource'); - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('LogicException'); + $this->expectException('LogicException'); $locator->locate('/some/path'); } diff --git a/lib/symfony/http-kernel/Tests/Controller/ArgumentResolverTest.php b/lib/symfony/http-kernel/Tests/Controller/ArgumentResolverTest.php index 8c900fb92..a964aaeb5 100644 --- a/lib/symfony/http-kernel/Tests/Controller/ArgumentResolverTest.php +++ b/lib/symfony/http-kernel/Tests/Controller/ArgumentResolverTest.php @@ -167,10 +167,10 @@ class ArgumentResolverTest extends TestCase /** * @requires PHP 5.6 - * @expectedException \InvalidArgumentException */ public function testGetVariadicArgumentsWithoutArrayInRequest() { + $this->expectException('InvalidArgumentException'); $request = Request::create('/'); $request->attributes->set('foo', 'foo'); $request->attributes->set('bar', 'foo'); @@ -181,10 +181,10 @@ class ArgumentResolverTest extends TestCase /** * @requires PHP 5.6 - * @expectedException \InvalidArgumentException */ public function testGetArgumentWithoutArray() { + $this->expectException('InvalidArgumentException'); $factory = new ArgumentMetadataFactory(); $valueResolver = $this->getMockBuilder(ArgumentValueResolverInterface::class)->getMock(); $resolver = new ArgumentResolver($factory, [$valueResolver]); @@ -199,11 +199,9 @@ class ArgumentResolverTest extends TestCase $resolver->getArguments($request, $controller); } - /** - * @expectedException \RuntimeException - */ public function testIfExceptionIsThrownWhenMissingAnArgument() { + $this->expectException('RuntimeException'); $request = Request::create('/'); $controller = [$this, 'controllerWithFoo']; @@ -266,11 +264,9 @@ class ArgumentResolverTest extends TestCase $this->assertEquals([$session], self::$resolver->getArguments($request, $controller)); } - /** - * @expectedException \RuntimeException - */ public function testGetSessionMissMatchWithInterface() { + $this->expectException('RuntimeException'); $session = $this->getMockBuilder(SessionInterface::class)->getMock(); $request = Request::create('/'); $request->setSession($session); @@ -279,11 +275,9 @@ class ArgumentResolverTest extends TestCase self::$resolver->getArguments($request, $controller); } - /** - * @expectedException \RuntimeException - */ public function testGetSessionMissMatchWithImplementation() { + $this->expectException('RuntimeException'); $session = new Session(new MockArraySessionStorage()); $request = Request::create('/'); $request->setSession($session); @@ -292,11 +286,9 @@ class ArgumentResolverTest extends TestCase self::$resolver->getArguments($request, $controller); } - /** - * @expectedException \RuntimeException - */ public function testGetSessionMissMatchOnNull() { + $this->expectException('RuntimeException'); $request = Request::create('/'); $controller = [$this, 'controllerWithExtendingSession']; diff --git a/lib/symfony/http-kernel/Tests/Controller/ContainerControllerResolverTest.php b/lib/symfony/http-kernel/Tests/Controller/ContainerControllerResolverTest.php index 098b89f9e..1f8ddb831 100644 --- a/lib/symfony/http-kernel/Tests/Controller/ContainerControllerResolverTest.php +++ b/lib/symfony/http-kernel/Tests/Controller/ContainerControllerResolverTest.php @@ -112,12 +112,10 @@ class ContainerControllerResolverTest extends ControllerResolverTest $this->assertSame([NonInstantiableController::class, 'action'], $controller); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Controller "Symfony\Component\HttpKernel\Tests\Controller\ImpossibleConstructController" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"? - */ public function testNonConstructController() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Controller "Symfony\Component\HttpKernel\Tests\Controller\ImpossibleConstructController" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?'); $container = $this->getMockBuilder(Container::class)->getMock(); $container->expects($this->at(0)) ->method('has') @@ -179,12 +177,10 @@ class ContainerControllerResolverTest extends ControllerResolverTest $this->assertSame([$service, 'action'], $controller); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Controller "app.my_controller" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"? - */ public function testExceptionWhenUsingRemovedControllerService() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Controller "app.my_controller" cannot be fetched from the container because it is private. Did you forget to tag the service with "controller.service_arguments"?'); $container = $this->getMockBuilder(Container::class)->getMock(); $container->expects($this->at(0)) ->method('has') @@ -205,12 +201,10 @@ class ContainerControllerResolverTest extends ControllerResolverTest $resolver->getController($request); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage Controller "app.my_controller" cannot be called without a method name. Did you forget an "__invoke" method? - */ public function testExceptionWhenUsingControllerWithoutAnInvokeMethod() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Controller "app.my_controller" cannot be called without a method name. Did you forget an "__invoke" method?'); $container = $this->getMockBuilder(Container::class)->getMock(); $container->expects($this->once()) ->method('has') @@ -237,12 +231,8 @@ class ContainerControllerResolverTest extends ControllerResolverTest { // All this logic needs to be duplicated, since calling parent::testGetControllerOnNonUndefinedFunction will override the expected excetion and not use the regex $resolver = $this->createControllerResolver(); - if (method_exists($this, 'expectException')) { - $this->expectException($exceptionName); - $this->expectExceptionMessageRegExp($exceptionMessage); - } else { - $this->setExpectedExceptionRegExp($exceptionName, $exceptionMessage); - } + $this->expectException($exceptionName); + $this->expectExceptionMessageRegExp($exceptionMessage); $request = Request::create('/'); $request->attributes->set('_controller', $controller); diff --git a/lib/symfony/http-kernel/Tests/Controller/ControllerResolverTest.php b/lib/symfony/http-kernel/Tests/Controller/ControllerResolverTest.php index 6a28eab26..e34427a32 100644 --- a/lib/symfony/http-kernel/Tests/Controller/ControllerResolverTest.php +++ b/lib/symfony/http-kernel/Tests/Controller/ControllerResolverTest.php @@ -90,11 +90,9 @@ class ControllerResolverTest extends TestCase $this->assertInstanceOf('Symfony\Component\HttpKernel\Tests\Controller\ControllerResolverTest', $controller); } - /** - * @expectedException \InvalidArgumentException - */ public function testGetControllerOnObjectWithoutInvokeMethod() { + $this->expectException('InvalidArgumentException'); $resolver = $this->createControllerResolver(); $request = Request::create('/'); @@ -118,12 +116,8 @@ class ControllerResolverTest extends TestCase public function testGetControllerOnNonUndefinedFunction($controller, $exceptionName = null, $exceptionMessage = null) { $resolver = $this->createControllerResolver(); - if (method_exists($this, 'expectException')) { - $this->expectException($exceptionName); - $this->expectExceptionMessage($exceptionMessage); - } else { - $this->setExpectedException($exceptionName, $exceptionMessage); - } + $this->expectException($exceptionName); + $this->expectExceptionMessage($exceptionMessage); $request = Request::create('/'); $request->attributes->set('_controller', $controller); @@ -234,11 +228,11 @@ class ControllerResolverTest extends TestCase } /** - * @expectedException \RuntimeException * @group legacy */ public function testIfExceptionIsThrownWhenMissingAnArgument() { + $this->expectException('RuntimeException'); $resolver = new ControllerResolver(); $request = Request::create('/'); diff --git a/lib/symfony/http-kernel/Tests/ControllerMetadata/ArgumentMetadataTest.php b/lib/symfony/http-kernel/Tests/ControllerMetadata/ArgumentMetadataTest.php index 05351445e..5ce4b1f76 100644 --- a/lib/symfony/http-kernel/Tests/ControllerMetadata/ArgumentMetadataTest.php +++ b/lib/symfony/http-kernel/Tests/ControllerMetadata/ArgumentMetadataTest.php @@ -32,11 +32,9 @@ class ArgumentMetadataTest extends TestCase $this->assertSame('default value', $argument->getDefaultValue()); } - /** - * @expectedException \LogicException - */ public function testDefaultValueUnavailable() { + $this->expectException('LogicException'); $argument = new ArgumentMetadata('foo', 'string', false, false, null, false); $this->assertFalse($argument->isNullable()); diff --git a/lib/symfony/http-kernel/Tests/DataCollector/LoggerDataCollectorTest.php b/lib/symfony/http-kernel/Tests/DataCollector/LoggerDataCollectorTest.php index ace4628e0..8b7fbe2a1 100644 --- a/lib/symfony/http-kernel/Tests/DataCollector/LoggerDataCollectorTest.php +++ b/lib/symfony/http-kernel/Tests/DataCollector/LoggerDataCollectorTest.php @@ -23,7 +23,7 @@ class LoggerDataCollectorTest extends TestCase ->getMockBuilder('Symfony\Component\HttpKernel\Log\DebugLoggerInterface') ->setMethods(['countErrors', 'getLogs', 'clear']) ->getMock(); - $logger->expects($this->once())->method('countErrors')->willReturn('foo'); + $logger->expects($this->once())->method('countErrors')->willReturn(123); $logger->expects($this->exactly(2))->method('getLogs')->willReturn([]); $c = new LoggerDataCollector($logger, __DIR__.'/'); diff --git a/lib/symfony/http-kernel/Tests/DataCollector/MemoryDataCollectorTest.php b/lib/symfony/http-kernel/Tests/DataCollector/MemoryDataCollectorTest.php index c434ed1e1..63dd62ce7 100644 --- a/lib/symfony/http-kernel/Tests/DataCollector/MemoryDataCollectorTest.php +++ b/lib/symfony/http-kernel/Tests/DataCollector/MemoryDataCollectorTest.php @@ -23,8 +23,8 @@ class MemoryDataCollectorTest extends TestCase $collector = new MemoryDataCollector(); $collector->collect(new Request(), new Response()); - $this->assertInternalType('integer', $collector->getMemory()); - $this->assertInternalType('integer', $collector->getMemoryLimit()); + $this->assertIsInt($collector->getMemory()); + $this->assertIsInt($collector->getMemoryLimit()); $this->assertSame('memory', $collector->getName()); } diff --git a/lib/symfony/http-kernel/Tests/DataCollector/TimeDataCollectorTest.php b/lib/symfony/http-kernel/Tests/DataCollector/TimeDataCollectorTest.php index e044e5e1a..9de9eb599 100644 --- a/lib/symfony/http-kernel/Tests/DataCollector/TimeDataCollectorTest.php +++ b/lib/symfony/http-kernel/Tests/DataCollector/TimeDataCollectorTest.php @@ -44,7 +44,7 @@ class TimeDataCollectorTest extends TestCase $this->assertEquals(0, $c->getStartTime()); $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock(); - $kernel->expects($this->once())->method('getStartTime')->willReturn(123456); + $kernel->expects($this->once())->method('getStartTime')->willReturn(123456.0); $c = new TimeDataCollector($kernel); $request = new Request(); diff --git a/lib/symfony/http-kernel/Tests/Debug/TraceableEventDispatcherTest.php b/lib/symfony/http-kernel/Tests/Debug/TraceableEventDispatcherTest.php index c66732a37..30c5ab5aa 100644 --- a/lib/symfony/http-kernel/Tests/Debug/TraceableEventDispatcherTest.php +++ b/lib/symfony/http-kernel/Tests/Debug/TraceableEventDispatcherTest.php @@ -61,15 +61,13 @@ class TraceableEventDispatcherTest extends TestCase public function testStopwatchStopControllerOnRequestEvent() { $stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch') - ->setMethods(['isStarted', 'stop', 'stopSection']) + ->setMethods(['isStarted', 'stop']) ->getMock(); $stopwatch->expects($this->once()) ->method('isStarted') ->willReturn(true); $stopwatch->expects($this->once()) ->method('stop'); - $stopwatch->expects($this->once()) - ->method('stopSection'); $dispatcher = new TraceableEventDispatcher(new EventDispatcher(), $stopwatch); diff --git a/lib/symfony/http-kernel/Tests/DependencyInjection/FragmentRendererPassTest.php b/lib/symfony/http-kernel/Tests/DependencyInjection/FragmentRendererPassTest.php index 087c66659..1d521368e 100644 --- a/lib/symfony/http-kernel/Tests/DependencyInjection/FragmentRendererPassTest.php +++ b/lib/symfony/http-kernel/Tests/DependencyInjection/FragmentRendererPassTest.php @@ -25,11 +25,10 @@ class FragmentRendererPassTest extends TestCase /** * Tests that content rendering not implementing FragmentRendererInterface * triggers an exception. - * - * @expectedException \InvalidArgumentException */ public function testContentRendererWithoutInterface() { + $this->expectException('InvalidArgumentException'); $builder = new ContainerBuilder(); $fragmentHandlerDefinition = $builder->register('fragment.handler'); $builder->register('my_content_renderer', 'Symfony\Component\DependencyInjection\Definition') diff --git a/lib/symfony/http-kernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php b/lib/symfony/http-kernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php index 6d0da5fcf..ef4c8b217 100644 --- a/lib/symfony/http-kernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php +++ b/lib/symfony/http-kernel/Tests/DependencyInjection/RegisterControllerArgumentLocatorsPassTest.php @@ -25,12 +25,10 @@ use Symfony\Component\HttpKernel\DependencyInjection\RegisterControllerArgumentL class RegisterControllerArgumentLocatorsPassTest extends TestCase { - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Class "Symfony\Component\HttpKernel\Tests\DependencyInjection\NotFound" used for service "foo" cannot be found. - */ public function testInvalidClass() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Class "Symfony\Component\HttpKernel\Tests\DependencyInjection\NotFound" used for service "foo" cannot be found.'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -42,12 +40,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Missing "action" attribute on tag "controller.service_arguments" {"argument":"bar"} for service "foo". - */ public function testNoAction() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Missing "action" attribute on tag "controller.service_arguments" {"argument":"bar"} for service "foo".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -59,12 +55,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Missing "argument" attribute on tag "controller.service_arguments" {"action":"fooAction"} for service "foo". - */ public function testNoArgument() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Missing "argument" attribute on tag "controller.service_arguments" {"action":"fooAction"} for service "foo".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -76,12 +70,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Missing "id" attribute on tag "controller.service_arguments" {"action":"fooAction","argument":"bar"} for service "foo". - */ public function testNoService() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Missing "id" attribute on tag "controller.service_arguments" {"action":"fooAction","argument":"bar"} for service "foo".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -93,12 +85,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid "action" attribute on tag "controller.service_arguments" for service "foo": no public "barAction()" method found on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController". - */ public function testInvalidMethod() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid "action" attribute on tag "controller.service_arguments" for service "foo": no public "barAction()" method found on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -110,12 +100,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Invalid "controller.service_arguments" tag for service "foo": method "fooAction()" has no "baz" argument on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController". - */ public function testInvalidArgument() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Invalid "controller.service_arguments" tag for service "foo": method "fooAction()" has no "baz" argument on class "Symfony\Component\HttpKernel\Tests\DependencyInjection\RegisterTestController".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -207,12 +195,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $this->assertSame(['foo:fooAction'], array_keys($locator)); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClass". Did you forget to add a use statement? - */ public function testExceptionOnNonExistentTypeHint() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClass". Did you forget to add a use statement?'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -223,12 +209,10 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase $pass->process($container); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException - * @expectedExceptionMessage Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassDifferentNamespaceController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Acme\NonExistentClass". - */ public function testExceptionOnNonExistentTypeHintDifferentNamespace() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\InvalidArgumentException'); + $this->expectExceptionMessage('Cannot determine controller argument for "Symfony\Component\HttpKernel\Tests\DependencyInjection\NonExistentClassDifferentNamespaceController::fooAction()": the $nonExistent argument is type-hinted with the non-existent class or interface: "Acme\NonExistentClass".'); $container = new ContainerBuilder(); $container->register('argument_resolver.service')->addArgument([]); @@ -272,7 +256,7 @@ class RegisterControllerArgumentLocatorsPassTest extends TestCase public function testControllersAreMadePublic() { $container = new ContainerBuilder(); - $resolver = $container->register('argument_resolver.service')->addArgument([]); + $container->register('argument_resolver.service')->addArgument([]); $container->register('foo', ArgumentWithoutTypeController::class) ->setPublic(false) diff --git a/lib/symfony/http-kernel/Tests/DependencyInjection/RemoveEmptyControllerArgumentLocatorsPassTest.php b/lib/symfony/http-kernel/Tests/DependencyInjection/RemoveEmptyControllerArgumentLocatorsPassTest.php index 713ab5441..84d735156 100644 --- a/lib/symfony/http-kernel/Tests/DependencyInjection/RemoveEmptyControllerArgumentLocatorsPassTest.php +++ b/lib/symfony/http-kernel/Tests/DependencyInjection/RemoveEmptyControllerArgumentLocatorsPassTest.php @@ -26,7 +26,7 @@ class RemoveEmptyControllerArgumentLocatorsPassTest extends TestCase $resolver = $container->register('argument_resolver.service')->addArgument([]); $container->register('stdClass', 'stdClass'); - $container->register(parent::class, 'stdClass'); + $container->register(TestCase::class, 'stdClass'); $container->register('c1', RemoveTestController1::class)->addTag('controller.service_arguments'); $container->register('c2', RemoveTestController2::class)->addTag('controller.service_arguments') ->addMethodCall('setTestCase', [new Reference('c1')]); diff --git a/lib/symfony/http-kernel/Tests/DependencyInjection/ResettableServicePassTest.php b/lib/symfony/http-kernel/Tests/DependencyInjection/ResettableServicePassTest.php index 9b23ad003..d3c686932 100644 --- a/lib/symfony/http-kernel/Tests/DependencyInjection/ResettableServicePassTest.php +++ b/lib/symfony/http-kernel/Tests/DependencyInjection/ResettableServicePassTest.php @@ -48,12 +48,10 @@ class ResettableServicePassTest extends TestCase ); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException - * @expectedExceptionMessage Tag kernel.reset requires the "method" attribute to be set. - */ public function testMissingMethod() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\RuntimeException'); + $this->expectExceptionMessage('Tag kernel.reset requires the "method" attribute to be set.'); $container = new ContainerBuilder(); $container->register(ResettableService::class) ->addTag('kernel.reset'); diff --git a/lib/symfony/http-kernel/Tests/EventListener/FragmentListenerTest.php b/lib/symfony/http-kernel/Tests/EventListener/FragmentListenerTest.php index 6408b1b21..0fb32eece 100644 --- a/lib/symfony/http-kernel/Tests/EventListener/FragmentListenerTest.php +++ b/lib/symfony/http-kernel/Tests/EventListener/FragmentListenerTest.php @@ -50,11 +50,9 @@ class FragmentListenerTest extends TestCase $this->assertEquals($expected, $request->attributes->all()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException - */ public function testAccessDeniedWithNonSafeMethods() { + $this->expectException('Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException'); $request = Request::create('http://example.com/_fragment', 'POST'); $listener = new FragmentListener(new UriSigner('foo')); @@ -63,11 +61,9 @@ class FragmentListenerTest extends TestCase $listener->onKernelRequest($event); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException - */ public function testAccessDeniedWithWrongSignature() { + $this->expectException('Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException'); $request = Request::create('http://example.com/_fragment', 'GET', [], [], [], ['REMOTE_ADDR' => '10.0.0.1']); $listener = new FragmentListener(new UriSigner('foo')); diff --git a/lib/symfony/http-kernel/Tests/EventListener/RouterListenerTest.php b/lib/symfony/http-kernel/Tests/EventListener/RouterListenerTest.php index 33f6ab959..dbe033d16 100644 --- a/lib/symfony/http-kernel/Tests/EventListener/RouterListenerTest.php +++ b/lib/symfony/http-kernel/Tests/EventListener/RouterListenerTest.php @@ -84,11 +84,9 @@ class RouterListenerTest extends TestCase return new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); } - /** - * @expectedException \InvalidArgumentException - */ public function testInvalidMatcher() { + $this->expectException('InvalidArgumentException'); new RouterListener(new \stdClass(), $this->requestStack); } @@ -206,14 +204,12 @@ class RouterListenerTest extends TestCase $request = Request::create('http://localhost/'); $response = $kernel->handle($request); $this->assertSame(404, $response->getStatusCode()); - $this->assertContains('Welcome', $response->getContent()); + $this->assertStringContainsString('Welcome', $response->getContent()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException - */ public function testRequestWithBadHost() { + $this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException'); $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(); $request = Request::create('http://bad host %22/'); $event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST); diff --git a/lib/symfony/http-kernel/Tests/EventListener/SessionListenerTest.php b/lib/symfony/http-kernel/Tests/EventListener/SessionListenerTest.php index f0bac6050..e8ab0deed 100644 --- a/lib/symfony/http-kernel/Tests/EventListener/SessionListenerTest.php +++ b/lib/symfony/http-kernel/Tests/EventListener/SessionListenerTest.php @@ -75,6 +75,9 @@ class SessionListenerTest extends TestCase $this->assertTrue($response->headers->hasCacheControlDirective('private')); $this->assertTrue($response->headers->hasCacheControlDirective('must-revalidate')); $this->assertSame('0', $response->headers->getCacheControlDirective('max-age')); + + $this->assertTrue($response->headers->has('Expires')); + $this->assertLessThanOrEqual((new \DateTime('now', new \DateTimeZone('UTC'))), (new \DateTime($response->headers->get('Expires')))); } public function testSurrogateMasterRequestIsPublic() @@ -104,10 +107,15 @@ class SessionListenerTest extends TestCase $this->assertFalse($response->headers->hasCacheControlDirective('must-revalidate')); $this->assertSame('30', $response->headers->getCacheControlDirective('max-age')); + $this->assertFalse($response->headers->has('Expires')); + $listener->onKernelResponse(new FilterResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST, $response)); $this->assertTrue($response->headers->hasCacheControlDirective('private')); $this->assertTrue($response->headers->hasCacheControlDirective('must-revalidate')); $this->assertSame('0', $response->headers->getCacheControlDirective('max-age')); + + $this->assertTrue($response->headers->has('Expires')); + $this->assertLessThanOrEqual((new \DateTime('now', new \DateTimeZone('UTC'))), (new \DateTime($response->headers->get('Expires')))); } } diff --git a/lib/symfony/http-kernel/Tests/EventListener/ValidateRequestListenerTest.php b/lib/symfony/http-kernel/Tests/EventListener/ValidateRequestListenerTest.php index fb7a4379b..7d63cb45f 100644 --- a/lib/symfony/http-kernel/Tests/EventListener/ValidateRequestListenerTest.php +++ b/lib/symfony/http-kernel/Tests/EventListener/ValidateRequestListenerTest.php @@ -26,11 +26,9 @@ class ValidateRequestListenerTest extends TestCase Request::setTrustedProxies([], -1); } - /** - * @expectedException \Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException - */ public function testListenerThrowsWhenMasterRequestHasInconsistentClientIps() { + $this->expectException('Symfony\Component\HttpFoundation\Exception\ConflictingHeadersException'); $dispatcher = new EventDispatcher(); $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(); diff --git a/lib/symfony/http-kernel/Tests/Fixtures/KernelForTest.php b/lib/symfony/http-kernel/Tests/Fixtures/KernelForTest.php index 88c34b023..8c3571281 100644 --- a/lib/symfony/http-kernel/Tests/Fixtures/KernelForTest.php +++ b/lib/symfony/http-kernel/Tests/Fixtures/KernelForTest.php @@ -34,4 +34,9 @@ class KernelForTest extends Kernel { return $this->booted; } + + public function getProjectDir() + { + return __DIR__; + } } diff --git a/lib/symfony/http-kernel/Tests/Fragment/EsiFragmentRendererTest.php b/lib/symfony/http-kernel/Tests/Fragment/EsiFragmentRendererTest.php index 52d855196..d8ba8aed8 100644 --- a/lib/symfony/http-kernel/Tests/Fragment/EsiFragmentRendererTest.php +++ b/lib/symfony/http-kernel/Tests/Fragment/EsiFragmentRendererTest.php @@ -77,11 +77,9 @@ class EsiFragmentRendererTest extends TestCase ); } - /** - * @expectedException \LogicException - */ public function testRenderControllerReferenceWithoutSignerThrowsException() { + $this->expectException('LogicException'); $strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy()); $request = Request::create('/'); @@ -91,11 +89,9 @@ class EsiFragmentRendererTest extends TestCase $strategy->render(new ControllerReference('main_controller'), $request); } - /** - * @expectedException \LogicException - */ public function testRenderAltControllerReferenceWithoutSignerThrowsException() { + $this->expectException('LogicException'); $strategy = new EsiFragmentRenderer(new Esi(), $this->getInlineStrategy()); $request = Request::create('/'); diff --git a/lib/symfony/http-kernel/Tests/Fragment/FragmentHandlerTest.php b/lib/symfony/http-kernel/Tests/Fragment/FragmentHandlerTest.php index 06ce785ea..6da4e73e3 100644 --- a/lib/symfony/http-kernel/Tests/Fragment/FragmentHandlerTest.php +++ b/lib/symfony/http-kernel/Tests/Fragment/FragmentHandlerTest.php @@ -36,31 +36,25 @@ class FragmentHandlerTest extends TestCase ; } - /** - * @expectedException \InvalidArgumentException - */ public function testRenderWhenRendererDoesNotExist() { + $this->expectException('InvalidArgumentException'); $handler = new FragmentHandler($this->requestStack); $handler->render('/', 'foo'); } - /** - * @expectedException \InvalidArgumentException - */ public function testRenderWithUnknownRenderer() { + $this->expectException('InvalidArgumentException'); $handler = $this->getHandler($this->returnValue(new Response('foo'))); $handler->render('/', 'bar'); } - /** - * @expectedException \RuntimeException - * @expectedExceptionMessage Error when rendering "http://localhost/" (Status code is 404). - */ public function testDeliverWithUnsuccessfulResponse() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('Error when rendering "http://localhost/" (Status code is 404).'); $handler = $this->getHandler($this->returnValue(new Response('foo', 404))); $handler->render('/', 'foo'); diff --git a/lib/symfony/http-kernel/Tests/Fragment/HIncludeFragmentRendererTest.php b/lib/symfony/http-kernel/Tests/Fragment/HIncludeFragmentRendererTest.php index 6125d95ff..43248f8e9 100644 --- a/lib/symfony/http-kernel/Tests/Fragment/HIncludeFragmentRendererTest.php +++ b/lib/symfony/http-kernel/Tests/Fragment/HIncludeFragmentRendererTest.php @@ -19,11 +19,9 @@ use Symfony\Component\HttpKernel\UriSigner; class HIncludeFragmentRendererTest extends TestCase { - /** - * @expectedException \LogicException - */ public function testRenderExceptionWhenControllerAndNoSigner() { + $this->expectException('LogicException'); $strategy = new HIncludeFragmentRenderer(); $strategy->render(new ControllerReference('main_controller', [], []), Request::create('/')); } diff --git a/lib/symfony/http-kernel/Tests/Fragment/InlineFragmentRendererTest.php b/lib/symfony/http-kernel/Tests/Fragment/InlineFragmentRendererTest.php index b2a2dcaef..0dfe8425f 100644 --- a/lib/symfony/http-kernel/Tests/Fragment/InlineFragmentRendererTest.php +++ b/lib/symfony/http-kernel/Tests/Fragment/InlineFragmentRendererTest.php @@ -111,11 +111,9 @@ class InlineFragmentRendererTest extends TestCase Request::setTrustedProxies([], -1); } - /** - * @expectedException \RuntimeException - */ public function testRenderExceptionNoIgnoreErrors() { + $this->expectException('RuntimeException'); $dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock(); $dispatcher->expects($this->never())->method('dispatch'); diff --git a/lib/symfony/http-kernel/Tests/Fragment/RoutableFragmentRendererTest.php b/lib/symfony/http-kernel/Tests/Fragment/RoutableFragmentRendererTest.php index c03e8c4a9..151adb0e9 100644 --- a/lib/symfony/http-kernel/Tests/Fragment/RoutableFragmentRendererTest.php +++ b/lib/symfony/http-kernel/Tests/Fragment/RoutableFragmentRendererTest.php @@ -56,11 +56,11 @@ class RoutableFragmentRendererTest extends TestCase } /** - * @expectedException \LogicException - * @dataProvider getGenerateFragmentUriDataWithNonScalar + * @dataProvider getGenerateFragmentUriDataWithNonScalar */ public function testGenerateFragmentUriWithNonScalar($controller) { + $this->expectException('LogicException'); $this->callGenerateFragmentUriMethod($controller, Request::create('/')); } diff --git a/lib/symfony/http-kernel/Tests/Fragment/SsiFragmentRendererTest.php b/lib/symfony/http-kernel/Tests/Fragment/SsiFragmentRendererTest.php index b2181725e..df30e6772 100644 --- a/lib/symfony/http-kernel/Tests/Fragment/SsiFragmentRendererTest.php +++ b/lib/symfony/http-kernel/Tests/Fragment/SsiFragmentRendererTest.php @@ -56,11 +56,9 @@ class SsiFragmentRendererTest extends TestCase ); } - /** - * @expectedException \LogicException - */ public function testRenderControllerReferenceWithoutSignerThrowsException() { + $this->expectException('LogicException'); $strategy = new SsiFragmentRenderer(new Ssi(), $this->getInlineStrategy()); $request = Request::create('/'); @@ -70,11 +68,9 @@ class SsiFragmentRendererTest extends TestCase $strategy->render(new ControllerReference('main_controller'), $request); } - /** - * @expectedException \LogicException - */ public function testRenderAltControllerReferenceWithoutSignerThrowsException() { + $this->expectException('LogicException'); $strategy = new SsiFragmentRenderer(new Ssi(), $this->getInlineStrategy()); $request = Request::create('/'); diff --git a/lib/symfony/http-kernel/Tests/HttpCache/EsiTest.php b/lib/symfony/http-kernel/Tests/HttpCache/EsiTest.php index 1fc8da8e2..2aca5459c 100644 --- a/lib/symfony/http-kernel/Tests/HttpCache/EsiTest.php +++ b/lib/symfony/http-kernel/Tests/HttpCache/EsiTest.php @@ -88,7 +88,7 @@ class EsiTest extends TestCase $request = Request::create('/'); $response = new Response(); $response->headers->set('Content-Type', 'text/plain'); - $esi->process($request, $response); + $this->assertSame($response, $esi->process($request, $response)); $this->assertFalse($response->headers->has('x-body-eval')); } @@ -99,7 +99,7 @@ class EsiTest extends TestCase $request = Request::create('/'); $response = new Response(' www.example.com Keep this'."\n www.example.com And this"); - $esi->process($request, $response); + $this->assertSame($response, $esi->process($request, $response)); $this->assertEquals(' Keep this And this', $response->getContent()); } @@ -110,7 +110,7 @@ class EsiTest extends TestCase $request = Request::create('/'); $response = new Response(' Keep this'); - $esi->process($request, $response); + $this->assertSame($response, $esi->process($request, $response)); $this->assertEquals(' Keep this', $response->getContent()); } @@ -121,23 +121,23 @@ class EsiTest extends TestCase $request = Request::create('/'); $response = new Response('foo '); - $esi->process($request, $response); + $this->assertSame($response, $esi->process($request, $response)); $this->assertEquals('foo surrogate->handle($this, \'...\', \'alt\', true) ?>'."\n", $response->getContent()); $this->assertEquals('ESI', $response->headers->get('x-body-eval')); $response = new Response('foo '); - $esi->process($request, $response); + $this->assertSame($response, $esi->process($request, $response)); $this->assertEquals('foo surrogate->handle($this, \'foo\\\'\', \'bar\\\'\', true) ?>'."\n", $response->getContent()); $response = new Response('foo '); - $esi->process($request, $response); + $this->assertSame($response, $esi->process($request, $response)); $this->assertEquals('foo surrogate->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent()); $response = new Response('foo '); - $esi->process($request, $response); + $this->assertSame($response, $esi->process($request, $response)); $this->assertEquals('foo surrogate->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent()); } @@ -148,21 +148,19 @@ class EsiTest extends TestCase $request = Request::create('/'); $response = new Response(''); - $esi->process($request, $response); + $this->assertSame($response, $esi->process($request, $response)); $this->assertEquals('php cript language=php>', $response->getContent()); } - /** - * @expectedException \RuntimeException - */ public function testProcessWhenNoSrcInAnEsi() { + $this->expectException('RuntimeException'); $esi = new Esi(); $request = Request::create('/'); $response = new Response('foo '); - $esi->process($request, $response); + $this->assertSame($response, $esi->process($request, $response)); } public function testProcessRemoveSurrogateControlHeader() @@ -172,16 +170,16 @@ class EsiTest extends TestCase $request = Request::create('/'); $response = new Response('foo '); $response->headers->set('Surrogate-Control', 'content="ESI/1.0"'); - $esi->process($request, $response); + $this->assertSame($response, $esi->process($request, $response)); $this->assertEquals('ESI', $response->headers->get('x-body-eval')); $response->headers->set('Surrogate-Control', 'no-store, content="ESI/1.0"'); - $esi->process($request, $response); + $this->assertSame($response, $esi->process($request, $response)); $this->assertEquals('ESI', $response->headers->get('x-body-eval')); $this->assertEquals('no-store', $response->headers->get('surrogate-control')); $response->headers->set('Surrogate-Control', 'content="ESI/1.0", no-store'); - $esi->process($request, $response); + $this->assertSame($response, $esi->process($request, $response)); $this->assertEquals('ESI', $response->headers->get('x-body-eval')); $this->assertEquals('no-store', $response->headers->get('surrogate-control')); } @@ -193,11 +191,9 @@ class EsiTest extends TestCase $this->assertEquals('foo', $esi->handle($cache, '/', '/alt', true)); } - /** - * @expectedException \RuntimeException - */ public function testHandleWhenResponseIsNot200() { + $this->expectException('RuntimeException'); $esi = new Esi(); $response = new Response('foo'); $response->setStatusCode(404); diff --git a/lib/symfony/http-kernel/Tests/HttpCache/HttpCacheTest.php b/lib/symfony/http-kernel/Tests/HttpCache/HttpCacheTest.php index 7b3cac78c..a50e09fb1 100644 --- a/lib/symfony/http-kernel/Tests/HttpCache/HttpCacheTest.php +++ b/lib/symfony/http-kernel/Tests/HttpCache/HttpCacheTest.php @@ -660,7 +660,7 @@ class HttpCacheTest extends HttpCacheTestCase $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); - $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); + $this->assertRegExp('/s-maxage=(2|3)/', $this->response->headers->get('Cache-Control')); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); @@ -668,7 +668,7 @@ class HttpCacheTest extends HttpCacheTestCase $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); - $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); + $this->assertRegExp('/s-maxage=(2|3)/', $this->response->headers->get('Cache-Control')); // expires the cache $values = $this->getMetaStorageValues(); @@ -688,7 +688,7 @@ class HttpCacheTest extends HttpCacheTestCase $this->assertTraceContains('invalid'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); - $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); + $this->assertRegExp('/s-maxage=(2|3)/', $this->response->headers->get('Cache-Control')); $this->setNextResponse(); @@ -698,7 +698,7 @@ class HttpCacheTest extends HttpCacheTestCase $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); - $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); + $this->assertRegExp('/s-maxage=(2|3)/', $this->response->headers->get('Cache-Control')); } public function testAssignsDefaultTtlWhenResponseHasNoFreshnessInformationAndAfterTtlWasExpiredWithStatus304() @@ -711,7 +711,7 @@ class HttpCacheTest extends HttpCacheTestCase $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); - $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); + $this->assertRegExp('/s-maxage=(2|3)/', $this->response->headers->get('Cache-Control')); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); @@ -739,7 +739,7 @@ class HttpCacheTest extends HttpCacheTestCase $this->assertTraceContains('store'); $this->assertTraceNotContains('miss'); $this->assertEquals('Hello World', $this->response->getContent()); - $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); + $this->assertRegExp('/s-maxage=(2|3)/', $this->response->headers->get('Cache-Control')); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); @@ -747,7 +747,7 @@ class HttpCacheTest extends HttpCacheTestCase $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); - $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); + $this->assertRegExp('/s-maxage=(2|3)/', $this->response->headers->get('Cache-Control')); } public function testDoesNotAssignDefaultTtlWhenResponseHasMustRevalidateDirective() diff --git a/lib/symfony/http-kernel/Tests/HttpCache/SsiTest.php b/lib/symfony/http-kernel/Tests/HttpCache/SsiTest.php index 79ed48cd0..f50005540 100644 --- a/lib/symfony/http-kernel/Tests/HttpCache/SsiTest.php +++ b/lib/symfony/http-kernel/Tests/HttpCache/SsiTest.php @@ -120,11 +120,9 @@ class SsiTest extends TestCase $this->assertEquals('php cript language=php>', $response->getContent()); } - /** - * @expectedException \RuntimeException - */ public function testProcessWhenNoSrcInAnSsi() { + $this->expectException('RuntimeException'); $ssi = new Ssi(); $request = Request::create('/'); @@ -160,11 +158,9 @@ class SsiTest extends TestCase $this->assertEquals('foo', $ssi->handle($cache, '/', '/alt', true)); } - /** - * @expectedException \RuntimeException - */ public function testHandleWhenResponseIsNot200() { + $this->expectException('RuntimeException'); $ssi = new Ssi(); $response = new Response('foo'); $response->setStatusCode(404); diff --git a/lib/symfony/http-kernel/Tests/HttpCache/StoreTest.php b/lib/symfony/http-kernel/Tests/HttpCache/StoreTest.php index fc47ff2c8..77cb34cfa 100644 --- a/lib/symfony/http-kernel/Tests/HttpCache/StoreTest.php +++ b/lib/symfony/http-kernel/Tests/HttpCache/StoreTest.php @@ -52,7 +52,7 @@ class StoreTest extends TestCase public function testUnlockFileThatDoesExist() { - $cacheKey = $this->storeSimpleEntry(); + $this->storeSimpleEntry(); $this->store->lock($this->request); $this->assertTrue($this->store->unlock($this->request)); @@ -92,7 +92,7 @@ class StoreTest extends TestCase { $cacheKey = $this->storeSimpleEntry(); $entries = $this->getStoreMetadata($cacheKey); - list($req, $res) = $entries[0]; + list(, $res) = $entries[0]; $this->assertEquals('en9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08', $res['x-content-digest'][0]); } @@ -208,7 +208,7 @@ class StoreTest extends TestCase { $req1 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar']); $res1 = new Response('test 1', 200, ['Vary' => 'Foo Bar']); - $key = $this->store->write($req1, $res1); + $this->store->write($req1, $res1); $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 1')), $this->store->lookup($req1)->getContent()); $req2 = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam']); @@ -229,7 +229,7 @@ class StoreTest extends TestCase $req = Request::create('/test', 'get', [], [], [], ['HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar']); $this->assertTrue($this->store->lock($req)); - $path = $this->store->lock($req); + $this->store->lock($req); $this->assertTrue($this->store->isLocked($req)); $this->store->unlock($req); diff --git a/lib/symfony/http-kernel/Tests/HttpKernelTest.php b/lib/symfony/http-kernel/Tests/HttpKernelTest.php index 01e32898e..af81f021e 100644 --- a/lib/symfony/http-kernel/Tests/HttpKernelTest.php +++ b/lib/symfony/http-kernel/Tests/HttpKernelTest.php @@ -30,21 +30,17 @@ use Symfony\Component\HttpKernel\KernelEvents; class HttpKernelTest extends TestCase { - /** - * @expectedException \RuntimeException - */ public function testHandleWhenControllerThrowsAnExceptionAndCatchIsTrue() { + $this->expectException('RuntimeException'); $kernel = $this->getHttpKernel(new EventDispatcher(), function () { throw new \RuntimeException(); }); $kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, true); } - /** - * @expectedException \RuntimeException - */ public function testHandleWhenControllerThrowsAnExceptionAndCatchIsFalseAndNoListenerIsRegistered() { + $this->expectException('RuntimeException'); $kernel = $this->getHttpKernel(new EventDispatcher(), function () { throw new \RuntimeException(); }); $kernel->handle(new Request(), HttpKernelInterface::MASTER_REQUEST, false); @@ -177,11 +173,9 @@ class HttpKernelTest extends TestCase $this->assertEquals('hello', $kernel->handle(new Request())->getContent()); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException - */ public function testHandleWhenNoControllerIsFound() { + $this->expectException('Symfony\Component\HttpKernel\Exception\NotFoundHttpException'); $dispatcher = new EventDispatcher(); $kernel = $this->getHttpKernel($dispatcher, false); @@ -229,11 +223,9 @@ class HttpKernelTest extends TestCase $this->assertResponseEquals(new Response('foo'), $kernel->handle(new Request())); } - /** - * @expectedException \LogicException - */ public function testHandleWhenTheControllerDoesNotReturnAResponse() { + $this->expectException('LogicException'); $dispatcher = new EventDispatcher(); $kernel = $this->getHttpKernel($dispatcher, function () { return 'foo'; }); @@ -331,11 +323,9 @@ class HttpKernelTest extends TestCase $kernel->handle($request, HttpKernelInterface::MASTER_REQUEST); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\BadRequestHttpException - */ public function testInconsistentClientIpsOnMasterRequests() { + $this->expectException('Symfony\Component\HttpKernel\Exception\BadRequestHttpException'); $request = new Request(); $request->setTrustedProxies(['1.1.1.1'], Request::HEADER_X_FORWARDED_FOR | Request::HEADER_FORWARDED); $request->server->set('REMOTE_ADDR', '1.1.1.1'); diff --git a/lib/symfony/http-kernel/Tests/KernelTest.php b/lib/symfony/http-kernel/Tests/KernelTest.php index 04d74ae0a..e4e2e0727 100644 --- a/lib/symfony/http-kernel/Tests/KernelTest.php +++ b/lib/symfony/http-kernel/Tests/KernelTest.php @@ -118,7 +118,7 @@ class KernelTest extends TestCase public function testBootSetsTheBootedFlagToTrue() { // use test kernel to access isBooted() - $kernel = $this->getKernelForTest(['initializeBundles', 'initializeContainer']); + $kernel = $this->getKernel(['initializeBundles', 'initializeContainer']); $kernel->boot(); $this->assertTrue($kernel->isBooted()); @@ -388,35 +388,27 @@ EOF; $this->assertEquals($expected, $kernel->serialize()); } - /** - * @expectedException \InvalidArgumentException - */ public function testLocateResourceThrowsExceptionWhenNameIsNotValid() { + $this->expectException('InvalidArgumentException'); $this->getKernel()->locateResource('Foo'); } - /** - * @expectedException \RuntimeException - */ public function testLocateResourceThrowsExceptionWhenNameIsUnsafe() { + $this->expectException('RuntimeException'); $this->getKernel()->locateResource('@FooBundle/../bar'); } - /** - * @expectedException \InvalidArgumentException - */ public function testLocateResourceThrowsExceptionWhenBundleDoesNotExist() { + $this->expectException('InvalidArgumentException'); $this->getKernel()->locateResource('@FooBundle/config/routing.xml'); } - /** - * @expectedException \InvalidArgumentException - */ public function testLocateResourceThrowsExceptionWhenResourceDoesNotExist() { + $this->expectException('InvalidArgumentException'); $kernel = $this->getKernel(['getBundle']); $kernel ->expects($this->once()) @@ -672,11 +664,11 @@ EOF; /** * @group legacy - * @expectedException \LogicException - * @expectedExceptionMessage Bundle "ChildCBundle" extends bundle "FooBar", which is not registered. */ public function testInitializeBundlesThrowsExceptionWhenAParentDoesNotExists() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Bundle "ChildCBundle" extends bundle "FooBar", which is not registered.'); $child = $this->getBundle(null, 'FooBar', 'ChildCBundle'); $kernel = $this->getKernel([], [$child]); $kernel->boot(); @@ -708,11 +700,11 @@ EOF; /** * @group legacy - * @expectedException \LogicException - * @expectedExceptionMessage Bundle "ParentCBundle" is directly extended by two bundles "ChildC2Bundle" and "ChildC1Bundle". */ public function testInitializeBundlesThrowsExceptionWhenABundleIsDirectlyExtendedByTwoBundles() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Bundle "ParentCBundle" is directly extended by two bundles "ChildC2Bundle" and "ChildC1Bundle".'); $parent = $this->getBundle(null, null, 'ParentCBundle'); $child1 = $this->getBundle(null, 'ParentCBundle', 'ChildC1Bundle'); $child2 = $this->getBundle(null, 'ParentCBundle', 'ChildC2Bundle'); @@ -723,13 +715,13 @@ EOF; /** * @group legacy - * @expectedException \LogicException - * @expectedExceptionMessage Trying to register two bundles with the same name "DuplicateName" */ public function testInitializeBundleThrowsExceptionWhenRegisteringTwoBundlesWithTheSameName() { - $fooBundle = $this->getBundle(null, null, 'FooBundle', 'DuplicateName'); - $barBundle = $this->getBundle(null, null, 'BarBundle', 'DuplicateName'); + $this->expectException('LogicException'); + $this->expectExceptionMessage('Trying to register two bundles with the same name "DuplicateName"'); + $fooBundle = $this->getBundle(__DIR__.'/Fixtures/FooBundle', null, 'FooBundle', 'DuplicateName'); + $barBundle = $this->getBundle(__DIR__.'/Fixtures/BarBundle', null, 'BarBundle', 'DuplicateName'); $kernel = $this->getKernel([], [$fooBundle, $barBundle]); $kernel->boot(); @@ -737,11 +729,11 @@ EOF; /** * @group legacy - * @expectedException \LogicException - * @expectedExceptionMessage Bundle "CircularRefBundle" can not extend itself. */ public function testInitializeBundleThrowsExceptionWhenABundleExtendsItself() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('Bundle "CircularRefBundle" can not extend itself.'); $circularRef = $this->getBundle(null, 'CircularRefBundle', 'CircularRefBundle'); $kernel = $this->getKernel([], [$circularRef]); @@ -906,7 +898,7 @@ EOF; */ public function testKernelStartTimeIsResetWhileBootingAlreadyBootedKernel() { - $kernel = $this->getKernelForTest(['initializeBundles'], true); + $kernel = $this->getKernel(['initializeBundles'], [], true); $kernel->boot(); $preReBoot = $kernel->getStartTime(); @@ -964,15 +956,15 @@ EOF; * * @return Kernel */ - protected function getKernel(array $methods = [], array $bundles = []) + protected function getKernel(array $methods = [], array $bundles = [], $debug = false) { $methods[] = 'registerBundles'; $kernel = $this - ->getMockBuilder('Symfony\Component\HttpKernel\Kernel') + ->getMockBuilder(KernelForTest::class) ->setMethods($methods) - ->setConstructorArgs(['test', false]) - ->getMockForAbstractClass() + ->setConstructorArgs(['test', $debug]) + ->getMock() ; $kernel->expects($this->any()) ->method('registerBundles') @@ -987,10 +979,11 @@ EOF; protected function getKernelForTest(array $methods = [], $debug = false) { - $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\Tests\Fixtures\KernelForTest') + $kernel = $this->getMockBuilder(KernelForTest::class) ->setConstructorArgs(['test', $debug]) ->setMethods($methods) - ->getMock(); + ->getMock() + ; $p = new \ReflectionProperty($kernel, 'rootDir'); $p->setAccessible(true); $p->setValue($kernel, __DIR__.'/Fixtures'); @@ -1011,6 +1004,11 @@ class TestKernel implements HttpKernelInterface public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true) { } + + public function getProjectDir() + { + return __DIR__.'/Fixtures'; + } } class CustomProjectDirKernel extends Kernel diff --git a/lib/symfony/http-kernel/Tests/Log/LoggerTest.php b/lib/symfony/http-kernel/Tests/Log/LoggerTest.php index 3a5a8ade5..7439ae137 100644 --- a/lib/symfony/http-kernel/Tests/Log/LoggerTest.php +++ b/lib/symfony/http-kernel/Tests/Log/LoggerTest.php @@ -107,27 +107,21 @@ class LoggerTest extends TestCase $this->assertSame([], $this->getLogs()); } - /** - * @expectedException \Psr\Log\InvalidArgumentException - */ public function testThrowsOnInvalidLevel() { + $this->expectException('Psr\Log\InvalidArgumentException'); $this->logger->log('invalid level', 'Foo'); } - /** - * @expectedException \Psr\Log\InvalidArgumentException - */ public function testThrowsOnInvalidMinLevel() { + $this->expectException('Psr\Log\InvalidArgumentException'); new Logger('invalid'); } - /** - * @expectedException \Psr\Log\InvalidArgumentException - */ public function testInvalidOutput() { + $this->expectException('Psr\Log\InvalidArgumentException'); new Logger(LogLevel::DEBUG, '/'); } @@ -145,7 +139,7 @@ class LoggerTest extends TestCase if (method_exists($this, 'createPartialMock')) { $dummy = $this->createPartialMock(DummyTest::class, ['__toString']); } else { - $dummy = $this->getMock(DummyTest::class, ['__toString']); + $dummy = $this->createPartialMock(DummyTest::class, ['__toString']); } $dummy->expects($this->atLeastOnce()) ->method('__toString') diff --git a/lib/symfony/http-kernel/Tests/Logger.php b/lib/symfony/http-kernel/Tests/Logger.php index 8ae756132..47529a2d3 100644 --- a/lib/symfony/http-kernel/Tests/Logger.php +++ b/lib/symfony/http-kernel/Tests/Logger.php @@ -22,6 +22,9 @@ class Logger implements LoggerInterface $this->clear(); } + /** + * @return array + */ public function getLogs($level = false) { return false === $level ? $this->logs : $this->logs[$level]; diff --git a/lib/symfony/http-kernel/Tests/UriSignerTest.php b/lib/symfony/http-kernel/Tests/UriSignerTest.php index 9b7fe08a9..b2eb59206 100644 --- a/lib/symfony/http-kernel/Tests/UriSignerTest.php +++ b/lib/symfony/http-kernel/Tests/UriSignerTest.php @@ -20,9 +20,9 @@ class UriSignerTest extends TestCase { $signer = new UriSigner('foobar'); - $this->assertContains('?_hash=', $signer->sign('http://example.com/foo')); - $this->assertContains('?_hash=', $signer->sign('http://example.com/foo?foo=bar')); - $this->assertContains('&foo=', $signer->sign('http://example.com/foo?foo=bar')); + $this->assertStringContainsString('?_hash=', $signer->sign('http://example.com/foo')); + $this->assertStringContainsString('?_hash=', $signer->sign('http://example.com/foo?foo=bar')); + $this->assertStringContainsString('&foo=', $signer->sign('http://example.com/foo?foo=bar')); } public function testCheck() diff --git a/lib/symfony/http-kernel/UriSigner.php b/lib/symfony/http-kernel/UriSigner.php index 481270da5..ffe31a212 100644 --- a/lib/symfony/http-kernel/UriSigner.php +++ b/lib/symfony/http-kernel/UriSigner.php @@ -79,7 +79,7 @@ class UriSigner $hash = $params[$this->parameter]; unset($params[$this->parameter]); - return $this->computeHash($this->buildUrl($url, $params)) === $hash; + return hash_equals($this->computeHash($this->buildUrl($url, $params)), $hash); } private function computeHash($uri) diff --git a/lib/symfony/http-kernel/composer.json b/lib/symfony/http-kernel/composer.json index f47f1162d..7f471c680 100644 --- a/lib/symfony/http-kernel/composer.json +++ b/lib/symfony/http-kernel/composer.json @@ -21,6 +21,7 @@ "symfony/http-foundation": "~3.4.12|~4.0.12|^4.1.1", "symfony/debug": "^3.3.3|~4.0", "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-php56": "~1.8", "psr/log": "~1.0" }, "require-dev": { diff --git a/lib/symfony/routing/Generator/UrlGenerator.php b/lib/symfony/routing/Generator/UrlGenerator.php index 3a826d86f..42c634922 100644 --- a/lib/symfony/routing/Generator/UrlGenerator.php +++ b/lib/symfony/routing/Generator/UrlGenerator.php @@ -123,6 +123,8 @@ class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInt * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route * @throws InvalidParameterException When a parameter value for a placeholder is not correct because * it does not match the requirement + * + * @return string|null */ protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = []) { @@ -150,7 +152,7 @@ class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInt $this->logger->error($message, ['parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]]]); } - return; + return null; } $url = $token[1].$mergedParams[$token[3]].$url; @@ -205,7 +207,7 @@ class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInt $this->logger->error($message, ['parameter' => $token[3], 'route' => $name, 'expected' => $token[2], 'given' => $mergedParams[$token[3]]]); } - return; + return null; } $routeHost = $token[1].$mergedParams[$token[3]].$routeHost; diff --git a/lib/symfony/routing/Loader/AnnotationClassLoader.php b/lib/symfony/routing/Loader/AnnotationClassLoader.php index 6b8a50efb..2a715e35d 100644 --- a/lib/symfony/routing/Loader/AnnotationClassLoader.php +++ b/lib/symfony/routing/Loader/AnnotationClassLoader.php @@ -15,6 +15,7 @@ use Doctrine\Common\Annotations\Reader; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\Config\Loader\LoaderResolverInterface; use Symfony\Component\Config\Resource\FileResource; +use Symfony\Component\Routing\Annotation\Route as RouteAnnotation; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; @@ -32,7 +33,6 @@ use Symfony\Component\Routing\RouteCollection; * recognizes several parameters: requirements, options, defaults, schemes, * methods, host, and name. The name parameter is mandatory. * Here is an example of how you should be able to use it: - * * /** * * @Route("/Blog") * * / @@ -44,7 +44,6 @@ use Symfony\Component\Routing\RouteCollection; * public function index() * { * } - * * /** * * @Route("/{id}", name="blog_post", requirements = {"id" = "\d+"}) * * / @@ -131,6 +130,10 @@ abstract class AnnotationClassLoader implements LoaderInterface return $collection; } + /** + * @param RouteAnnotation $annot or an object that exposes a similar interface + * @param array $globals + */ protected function addRoute(RouteCollection $collection, $annot, $globals, \ReflectionClass $class, \ReflectionMethod $method) { $name = $annot->getName(); @@ -192,9 +195,6 @@ abstract class AnnotationClassLoader implements LoaderInterface /** * Gets the default route name for a class method. * - * @param \ReflectionClass $class - * @param \ReflectionMethod $method - * * @return string */ protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method) diff --git a/lib/symfony/routing/Loader/AnnotationFileLoader.php b/lib/symfony/routing/Loader/AnnotationFileLoader.php index b155510ed..d8c10197d 100644 --- a/lib/symfony/routing/Loader/AnnotationFileLoader.php +++ b/lib/symfony/routing/Loader/AnnotationFileLoader.php @@ -46,7 +46,7 @@ class AnnotationFileLoader extends FileLoader * @param string $file A PHP file path * @param string|null $type The resource type * - * @return RouteCollection A RouteCollection instance + * @return RouteCollection|null A RouteCollection instance * * @throws \InvalidArgumentException When the file does not exist or its routes cannot be parsed */ @@ -58,7 +58,7 @@ class AnnotationFileLoader extends FileLoader if ($class = $this->findClass($path)) { $refl = new \ReflectionClass($class); if ($refl->isAbstract()) { - return; + return null; } $collection->addResource(new FileResource($path)); diff --git a/lib/symfony/routing/Loader/Configurator/RoutingConfigurator.php b/lib/symfony/routing/Loader/Configurator/RoutingConfigurator.php index 7614caea3..d0cc02d1c 100644 --- a/lib/symfony/routing/Loader/Configurator/RoutingConfigurator.php +++ b/lib/symfony/routing/Loader/Configurator/RoutingConfigurator.php @@ -39,7 +39,8 @@ class RoutingConfigurator final public function import($resource, $type = null, $ignoreErrors = false) { $this->loader->setCurrentDir(\dirname($this->path)); - $imported = $this->loader->import($resource, $type, $ignoreErrors, $this->file); + $imported = $this->loader->import($resource, $type, $ignoreErrors, $this->file) ?: []; + if (!\is_array($imported)) { return new ImportConfigurator($this->collection, $imported); } diff --git a/lib/symfony/routing/Loader/PhpFileLoader.php b/lib/symfony/routing/Loader/PhpFileLoader.php index d81e7e82e..d9ba59d51 100644 --- a/lib/symfony/routing/Loader/PhpFileLoader.php +++ b/lib/symfony/routing/Loader/PhpFileLoader.php @@ -40,7 +40,7 @@ class PhpFileLoader extends FileLoader // the closure forbids access to the private scope in the included file $loader = $this; - $load = \Closure::bind(function ($file) use ($loader) { + $load = \Closure::bind(static function ($file) use ($loader) { return include $file; }, null, ProtectedPhpFileLoader::class); diff --git a/lib/symfony/routing/Loader/XmlFileLoader.php b/lib/symfony/routing/Loader/XmlFileLoader.php index 444a08a77..29dfdb166 100644 --- a/lib/symfony/routing/Loader/XmlFileLoader.php +++ b/lib/symfony/routing/Loader/XmlFileLoader.php @@ -146,7 +146,8 @@ class XmlFileLoader extends FileLoader $this->setCurrentDir(\dirname($path)); - $imported = $this->import($resource, ('' !== $type ? $type : null), false, $file); + /** @var RouteCollection[] $imported */ + $imported = $this->import($resource, ('' !== $type ? $type : null), false, $file) ?: []; if (!\is_array($imported)) { $imported = [$imported]; @@ -261,7 +262,7 @@ class XmlFileLoader extends FileLoader private function parseDefaultsConfig(\DOMElement $element, $path) { if ($this->isElementValueNull($element)) { - return; + return null; } // Check for existing element nodes in the default element. There can @@ -298,7 +299,7 @@ class XmlFileLoader extends FileLoader private function parseDefaultNode(\DOMElement $node, $path) { if ($this->isElementValueNull($node)) { - return; + return null; } switch ($node->localName) { diff --git a/lib/symfony/routing/Loader/YamlFileLoader.php b/lib/symfony/routing/Loader/YamlFileLoader.php index bc21e9cb4..568827695 100644 --- a/lib/symfony/routing/Loader/YamlFileLoader.php +++ b/lib/symfony/routing/Loader/YamlFileLoader.php @@ -158,7 +158,7 @@ class YamlFileLoader extends FileLoader $this->setCurrentDir(\dirname($path)); - $imported = $this->import($config['resource'], $type, false, $file); + $imported = $this->import($config['resource'], $type, false, $file) ?: []; if (!\is_array($imported)) { $imported = [$imported]; diff --git a/lib/symfony/routing/Matcher/Dumper/StaticPrefixCollection.php b/lib/symfony/routing/Matcher/Dumper/StaticPrefixCollection.php index 15c47051f..c8497c36f 100644 --- a/lib/symfony/routing/Matcher/Dumper/StaticPrefixCollection.php +++ b/lib/symfony/routing/Matcher/Dumper/StaticPrefixCollection.php @@ -114,7 +114,7 @@ class StaticPrefixCollection $commonPrefix = $this->detectCommonPrefix($prefix, $itemPrefix); if (!$commonPrefix) { - return; + return null; } $child = new self($commonPrefix); diff --git a/lib/symfony/routing/Matcher/TraceableUrlMatcher.php b/lib/symfony/routing/Matcher/TraceableUrlMatcher.php index 3c3c4bfcf..0d7087465 100644 --- a/lib/symfony/routing/Matcher/TraceableUrlMatcher.php +++ b/lib/symfony/routing/Matcher/TraceableUrlMatcher.php @@ -52,10 +52,41 @@ class TraceableUrlMatcher extends UrlMatcher protected function matchCollection($pathinfo, RouteCollection $routes) { + // HEAD and GET are equivalent as per RFC + if ('HEAD' === $method = $this->context->getMethod()) { + $method = 'GET'; + } + $supportsTrailingSlash = '/' !== $pathinfo && '' !== $pathinfo && $this instanceof RedirectableUrlMatcherInterface; + foreach ($routes as $name => $route) { $compiledRoute = $route->compile(); + $staticPrefix = $compiledRoute->getStaticPrefix(); + $requiredMethods = $route->getMethods(); - if (!preg_match($compiledRoute->getRegex(), $pathinfo, $matches)) { + // check the static prefix of the URL first. Only use the more expensive preg_match when it matches + if ('' === $staticPrefix || 0 === strpos($pathinfo, $staticPrefix)) { + // no-op + } elseif (!$supportsTrailingSlash || ($requiredMethods && !\in_array('GET', $requiredMethods)) || 'GET' !== $method) { + $this->addTrace(sprintf('Path "%s" does not match', $route->getPath()), self::ROUTE_DOES_NOT_MATCH, $name, $route); + continue; + } elseif ('/' === substr($staticPrefix, -1) && substr($staticPrefix, 0, -1) === $pathinfo) { + $this->addTrace('Route matches!', self::ROUTE_MATCHES, $name, $route); + + return $this->allow = []; + } else { + $this->addTrace(sprintf('Path "%s" does not match', $route->getPath()), self::ROUTE_DOES_NOT_MATCH, $name, $route); + continue; + } + $regex = $compiledRoute->getRegex(); + + if ($supportsTrailingSlash && $pos = strpos($regex, '/$')) { + $regex = substr($regex, 0, $pos).'/?$'.substr($regex, $pos + 2); + $hasTrailingSlash = true; + } else { + $hasTrailingSlash = false; + } + + if (!preg_match($regex, $pathinfo, $matches)) { // does it match without any requirements? $r = new Route($route->getPath(), $route->getDefaults(), [], $route->getOptions()); $cr = $r->compile(); @@ -79,54 +110,52 @@ class TraceableUrlMatcher extends UrlMatcher continue; } - // check host requirement + if ($hasTrailingSlash && '/' !== substr($pathinfo, -1)) { + if ((!$requiredMethods || \in_array('GET', $requiredMethods)) && 'GET' === $method) { + $this->addTrace('Route matches!', self::ROUTE_MATCHES, $name, $route); + + return $this->allow = []; + } + $this->addTrace(sprintf('Method "%s" does not match any of the required methods (%s)', $this->context->getMethod(), implode(', ', $requiredMethods)), self::ROUTE_ALMOST_MATCHES, $name, $route); + continue; + } + $hostMatches = []; if ($compiledRoute->getHostRegex() && !preg_match($compiledRoute->getHostRegex(), $this->context->getHost(), $hostMatches)) { $this->addTrace(sprintf('Host "%s" does not match the requirement ("%s")', $this->context->getHost(), $route->getHost()), self::ROUTE_ALMOST_MATCHES, $name, $route); + continue; + } + + $status = $this->handleRouteRequirements($pathinfo, $name, $route); + + if (self::REQUIREMENT_MISMATCH === $status[0]) { + if ($route->getCondition()) { + $this->addTrace(sprintf('Condition "%s" does not evaluate to "true"', $route->getCondition()), self::ROUTE_ALMOST_MATCHES, $name, $route); + } else { + $this->addTrace(sprintf('Scheme "%s" does not match any of the required schemes (%s); the user will be redirected to first required scheme', $this->getContext()->getScheme(), implode(', ', $route->getSchemes())), self::ROUTE_ALMOST_MATCHES, $name, $route); + } continue; } // check HTTP method requirement - if ($requiredMethods = $route->getMethods()) { - // HEAD and GET are equivalent as per RFC - if ('HEAD' === $method = $this->context->getMethod()) { - $method = 'GET'; - } - + if ($requiredMethods) { if (!\in_array($method, $requiredMethods)) { - $this->allow = array_merge($this->allow, $requiredMethods); - + if (self::REQUIREMENT_MATCH === $status[0]) { + $this->allow = array_merge($this->allow, $requiredMethods); + } $this->addTrace(sprintf('Method "%s" does not match any of the required methods (%s)', $this->context->getMethod(), implode(', ', $requiredMethods)), self::ROUTE_ALMOST_MATCHES, $name, $route); continue; } } - // check condition - if ($condition = $route->getCondition()) { - if (!$this->getExpressionLanguage()->evaluate($condition, ['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; - } - } - - // check HTTP scheme requirement - if ($requiredSchemes = $route->getSchemes()) { - $scheme = $this->context->getScheme(); - - if (!$route->hasScheme($scheme)) { - $this->addTrace(sprintf('Scheme "%s" does not match any of the required schemes (%s); the user will be redirected to first required scheme', $scheme, implode(', ', $requiredSchemes)), self::ROUTE_ALMOST_MATCHES, $name, $route); - - return true; - } - } - $this->addTrace('Route matches!', self::ROUTE_MATCHES, $name, $route); - return true; + return $this->getAttributes($route, $name, array_replace($matches, $hostMatches, isset($status[1]) ? $status[1] : [])); } + + return []; } private function addTrace($log, $level = self::ROUTE_DOES_NOT_MATCH, $name = null, $route = null) diff --git a/lib/symfony/routing/RouteCollectionBuilder.php b/lib/symfony/routing/RouteCollectionBuilder.php index 800e448cf..45f9e3d39 100644 --- a/lib/symfony/routing/RouteCollectionBuilder.php +++ b/lib/symfony/routing/RouteCollectionBuilder.php @@ -127,7 +127,6 @@ class RouteCollectionBuilder /** * Adds a Route object to the builder. * - * @param Route $route * @param string|null $name * * @return $this diff --git a/lib/symfony/routing/Router.php b/lib/symfony/routing/Router.php index 27c32e14a..a85fa6d76 100644 --- a/lib/symfony/routing/Router.php +++ b/lib/symfony/routing/Router.php @@ -263,9 +263,9 @@ class Router implements RouterInterface, RequestMatcherInterface } /** - * Gets the UrlMatcher instance associated with this Router. + * Gets the UrlMatcher or RequestMatcher instance associated with this Router. * - * @return UrlMatcherInterface A UrlMatcherInterface instance + * @return UrlMatcherInterface|RequestMatcherInterface */ public function getMatcher() { diff --git a/lib/symfony/routing/RouterInterface.php b/lib/symfony/routing/RouterInterface.php index a10ae34e0..8a3e33dc2 100644 --- a/lib/symfony/routing/RouterInterface.php +++ b/lib/symfony/routing/RouterInterface.php @@ -26,6 +26,9 @@ interface RouterInterface extends UrlMatcherInterface, UrlGeneratorInterface /** * Gets the RouteCollection instance associated with this Router. * + * WARNING: This method should never be used at runtime as it is SLOW. + * You might use it in a cache warmer though. + * * @return RouteCollection A RouteCollection instance */ public function getRouteCollection(); diff --git a/lib/symfony/routing/Tests/Annotation/RouteTest.php b/lib/symfony/routing/Tests/Annotation/RouteTest.php index 2cbfd7390..b698be8f6 100644 --- a/lib/symfony/routing/Tests/Annotation/RouteTest.php +++ b/lib/symfony/routing/Tests/Annotation/RouteTest.php @@ -16,12 +16,10 @@ use Symfony\Component\Routing\Annotation\Route; class RouteTest extends TestCase { - /** - * @expectedException \BadMethodCallException - */ public function testInvalidRouteParameter() { - $route = new Route(['foo' => 'bar']); + $this->expectException('BadMethodCallException'); + new Route(['foo' => 'bar']); } /** diff --git a/lib/symfony/routing/Tests/Fixtures/AnnotatedClasses/FooTrait.php b/lib/symfony/routing/Tests/Fixtures/AnnotatedClasses/FooTrait.php index ee8f4b071..c06fb43f6 100644 --- a/lib/symfony/routing/Tests/Fixtures/AnnotatedClasses/FooTrait.php +++ b/lib/symfony/routing/Tests/Fixtures/AnnotatedClasses/FooTrait.php @@ -6,7 +6,7 @@ trait FooTrait { public function doBar() { - $baz = self::class; + self::class; if (true) { } } diff --git a/lib/symfony/routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.php b/lib/symfony/routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.php index a6a47b4ba..4e725fa8b 100644 --- a/lib/symfony/routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.php +++ b/lib/symfony/routing/Tests/Generator/Dumper/PhpGeneratorDumperTest.php @@ -115,11 +115,9 @@ class PhpGeneratorDumperTest extends TestCase $this->assertEquals('/app.php/testing2', $relativeUrlWithoutParameter); } - /** - * @expectedException \InvalidArgumentException - */ public function testDumpWithoutRoutes() { + $this->expectException('InvalidArgumentException'); file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(['class' => 'WithoutRoutesUrlGenerator'])); include $this->testTmpFilepath; @@ -128,18 +126,16 @@ class PhpGeneratorDumperTest extends TestCase $projectUrlGenerator->generate('Test', []); } - /** - * @expectedException \Symfony\Component\Routing\Exception\RouteNotFoundException - */ public function testGenerateNonExistingRoute() { + $this->expectException('Symfony\Component\Routing\Exception\RouteNotFoundException'); $this->routeCollection->add('Test', new Route('/test')); file_put_contents($this->testTmpFilepath, $this->generatorDumper->dump(['class' => 'NonExistingRoutesUrlGenerator'])); include $this->testTmpFilepath; $projectUrlGenerator = new \NonExistingRoutesUrlGenerator(new RequestContext()); - $url = $projectUrlGenerator->generate('NonExisting', []); + $projectUrlGenerator->generate('NonExisting', []); } public function testDumpForRouteWithDefaults() diff --git a/lib/symfony/routing/Tests/Generator/UrlGeneratorTest.php b/lib/symfony/routing/Tests/Generator/UrlGeneratorTest.php index a4d754cb1..de7c4f5ed 100644 --- a/lib/symfony/routing/Tests/Generator/UrlGeneratorTest.php +++ b/lib/symfony/routing/Tests/Generator/UrlGeneratorTest.php @@ -76,11 +76,9 @@ class UrlGeneratorTest extends TestCase $this->assertEquals('/app.php/testing', $url); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testRelativeUrlWithNullParameterButNotOptional() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/testing/{foo}/bar', ['foo' => null])); // This must raise an exception because the default requirement for "foo" is "[^/]+" which is not met with these params. // Generating path "/testing//bar" would be wrong as matching this route would fail. @@ -162,38 +160,30 @@ class UrlGeneratorTest extends TestCase $this->assertSame('/app.php/de', $url); } - /** - * @expectedException \Symfony\Component\Routing\Exception\RouteNotFoundException - */ public function testGenerateWithoutRoutes() { + $this->expectException('Symfony\Component\Routing\Exception\RouteNotFoundException'); $routes = $this->getRoutes('foo', new Route('/testing/{foo}')); $this->getGenerator($routes)->generate('test', [], UrlGeneratorInterface::ABSOLUTE_URL); } - /** - * @expectedException \Symfony\Component\Routing\Exception\MissingMandatoryParametersException - */ public function testGenerateForRouteWithoutMandatoryParameter() { + $this->expectException('Symfony\Component\Routing\Exception\MissingMandatoryParametersException'); $routes = $this->getRoutes('test', new Route('/testing/{foo}')); $this->getGenerator($routes)->generate('test', [], UrlGeneratorInterface::ABSOLUTE_URL); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testGenerateForRouteWithInvalidOptionalParameter() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/testing/{foo}', ['foo' => '1'], ['foo' => 'd+'])); $this->getGenerator($routes)->generate('test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_URL); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testGenerateForRouteWithInvalidParameter() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/testing/{foo}', [], ['foo' => '1|2'])); $this->getGenerator($routes)->generate('test', ['foo' => '0'], UrlGeneratorInterface::ABSOLUTE_URL); } @@ -225,29 +215,23 @@ class UrlGeneratorTest extends TestCase $this->assertSame('/app.php/testing/bar', $generator->generate('test', ['foo' => 'bar'])); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testGenerateForRouteWithInvalidMandatoryParameter() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/testing/{foo}', [], ['foo' => 'd+'])); $this->getGenerator($routes)->generate('test', ['foo' => 'bar'], UrlGeneratorInterface::ABSOLUTE_URL); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testGenerateForRouteWithInvalidUtf8Parameter() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/testing/{foo}', [], ['foo' => '\pL+'], ['utf8' => true])); $this->getGenerator($routes)->generate('test', ['foo' => 'abc123'], UrlGeneratorInterface::ABSOLUTE_URL); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testRequiredParamAndEmptyPassed() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/{slug}', [], ['slug' => '.+'])); $this->getGenerator($routes)->generate('test', ['slug' => '']); } @@ -368,7 +352,7 @@ class UrlGeneratorTest extends TestCase // The default requirement for 'x' should not allow the separator '.' in this case because it would otherwise match everything // and following optional variables like _format could never match. - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\Routing\Exception\InvalidParameterException'); + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $generator->generate('test', ['x' => 'do.t', 'y' => '123', 'z' => 'bar', '_format' => 'xml']); } @@ -397,20 +381,16 @@ class UrlGeneratorTest extends TestCase $this->assertSame('/app.php/index.mobile.html', $generator->generate('test', ['page' => 'index', '_format' => 'mobile.html'])); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testDefaultRequirementOfVariableDisallowsSlash() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/{page}.{_format}')); $this->getGenerator($routes)->generate('test', ['page' => 'index', '_format' => 'sl/ash']); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testDefaultRequirementOfVariableDisallowsNextSeparator() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/{page}.{_format}')); $this->getGenerator($routes)->generate('test', ['page' => 'do.t', '_format' => 'html']); } @@ -436,29 +416,23 @@ class UrlGeneratorTest extends TestCase $this->assertEquals('http://fr.example.com/app.php/Fabien', $this->getGenerator($routes, ['host' => 'fr.example.com'])->generate('test', ['name' => 'Fabien', 'locale' => 'fr'], UrlGeneratorInterface::ABSOLUTE_URL)); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testUrlWithInvalidParameterInHost() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/', [], ['foo' => 'bar'], [], '{foo}.example.com')); $this->getGenerator($routes)->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testUrlWithInvalidParameterInHostWhenParamHasADefaultValue() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/', ['foo' => 'bar'], ['foo' => 'bar'], [], '{foo}.example.com')); $this->getGenerator($routes)->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH); } - /** - * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException - */ public function testUrlWithInvalidParameterEqualsDefaultValueInHost() { + $this->expectException('Symfony\Component\Routing\Exception\InvalidParameterException'); $routes = $this->getRoutes('test', new Route('/', ['foo' => 'baz'], ['foo' => 'bar'], [], '{foo}.example.com')); $this->getGenerator($routes)->generate('test', ['foo' => 'baz'], UrlGeneratorInterface::ABSOLUTE_PATH); } diff --git a/lib/symfony/routing/Tests/Loader/AnnotationClassLoaderTest.php b/lib/symfony/routing/Tests/Loader/AnnotationClassLoaderTest.php index 7726dc6fa..b13f23cf4 100644 --- a/lib/symfony/routing/Tests/Loader/AnnotationClassLoaderTest.php +++ b/lib/symfony/routing/Tests/Loader/AnnotationClassLoaderTest.php @@ -26,19 +26,15 @@ class AnnotationClassLoaderTest extends AbstractAnnotationLoaderTest $this->loader = $this->getClassLoader($this->reader); } - /** - * @expectedException \InvalidArgumentException - */ public function testLoadMissingClass() { + $this->expectException('InvalidArgumentException'); $this->loader->load('MissingClass'); } - /** - * @expectedException \InvalidArgumentException - */ public function testLoadAbstractClass() { + $this->expectException('InvalidArgumentException'); $this->loader->load('Symfony\Component\Routing\Tests\Fixtures\AnnotatedClasses\AbstractClass'); } diff --git a/lib/symfony/routing/Tests/Loader/AnnotationFileLoaderTest.php b/lib/symfony/routing/Tests/Loader/AnnotationFileLoaderTest.php index 066b7c45f..0b1175f60 100644 --- a/lib/symfony/routing/Tests/Loader/AnnotationFileLoaderTest.php +++ b/lib/symfony/routing/Tests/Loader/AnnotationFileLoaderTest.php @@ -35,9 +35,6 @@ class AnnotationFileLoaderTest extends AbstractAnnotationLoaderTest $this->loader->load(__DIR__.'/../Fixtures/AnnotatedClasses/FooClass.php'); } - /** - * @requires PHP 5.4 - */ public function testLoadTraitWithClassConstant() { $this->reader->expects($this->never())->method('getClassAnnotation'); @@ -45,12 +42,10 @@ class AnnotationFileLoaderTest extends AbstractAnnotationLoaderTest $this->loader->load(__DIR__.'/../Fixtures/AnnotatedClasses/FooTrait.php'); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Did you forgot to add the "expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Did you forgot to add the "loader->load(__DIR__.'/../Fixtures/OtherAnnotatedClasses/NoStartTagClass.php'); } diff --git a/lib/symfony/routing/Tests/Loader/ObjectRouteLoaderTest.php b/lib/symfony/routing/Tests/Loader/ObjectRouteLoaderTest.php index 774e1a1fe..64187744e 100644 --- a/lib/symfony/routing/Tests/Loader/ObjectRouteLoaderTest.php +++ b/lib/symfony/routing/Tests/Loader/ObjectRouteLoaderTest.php @@ -41,11 +41,11 @@ class ObjectRouteLoaderTest extends TestCase } /** - * @expectedException \InvalidArgumentException * @dataProvider getBadResourceStrings */ public function testExceptionWithoutSyntax($resourceString) { + $this->expectException('InvalidArgumentException'); $loader = new ObjectRouteLoaderForTest(); $loader->load($resourceString); } @@ -59,31 +59,25 @@ class ObjectRouteLoaderTest extends TestCase ]; } - /** - * @expectedException \LogicException - */ public function testExceptionOnNoObjectReturned() { + $this->expectException('LogicException'); $loader = new ObjectRouteLoaderForTest(); $loader->loaderMap = ['my_service' => 'NOT_AN_OBJECT']; $loader->load('my_service:method'); } - /** - * @expectedException \BadMethodCallException - */ public function testExceptionOnBadMethod() { + $this->expectException('BadMethodCallException'); $loader = new ObjectRouteLoaderForTest(); $loader->loaderMap = ['my_service' => new \stdClass()]; $loader->load('my_service:method'); } - /** - * @expectedException \LogicException - */ public function testExceptionOnMethodNotReturningCollection() { + $this->expectException('LogicException'); $service = $this->getMockBuilder('stdClass') ->setMethods(['loadRoutes']) ->getMock(); diff --git a/lib/symfony/routing/Tests/Loader/XmlFileLoaderTest.php b/lib/symfony/routing/Tests/Loader/XmlFileLoaderTest.php index 9a061b295..128bb54fb 100644 --- a/lib/symfony/routing/Tests/Loader/XmlFileLoaderTest.php +++ b/lib/symfony/routing/Tests/Loader/XmlFileLoaderTest.php @@ -104,21 +104,21 @@ class XmlFileLoaderTest extends TestCase } /** - * @expectedException \InvalidArgumentException * @dataProvider getPathsToInvalidFiles */ public function testLoadThrowsExceptionWithInvalidFile($filePath) { + $this->expectException('InvalidArgumentException'); $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); $loader->load($filePath); } /** - * @expectedException \InvalidArgumentException * @dataProvider getPathsToInvalidFiles */ public function testLoadThrowsExceptionWithInvalidFileEvenWithoutSchemaValidation($filePath) { + $this->expectException('InvalidArgumentException'); $loader = new CustomXmlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); $loader->load($filePath); } @@ -128,12 +128,10 @@ class XmlFileLoaderTest extends TestCase return [['nonvalidnode.xml'], ['nonvalidroute.xml'], ['nonvalid.xml'], ['missing_id.xml'], ['missing_path.xml']]; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage Document types are not allowed. - */ public function testDocTypeIsNotAllowed() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('Document types are not allowed.'); $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); $loader->load('withdoctype.xml'); } @@ -338,12 +336,10 @@ class XmlFileLoaderTest extends TestCase $this->assertSame('AppBundle:Blog:list', $route->getDefault('_controller')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /The routing file "[^"]*" must not specify both the "controller" attribute and the defaults key "_controller" for "app_blog"/ - */ public function testOverrideControllerInDefaults() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The routing file "[^"]*" must not specify both the "controller" attribute and the defaults key "_controller" for "app_blog"/'); $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); $loader->load('override_defaults.xml'); } @@ -372,12 +368,10 @@ class XmlFileLoaderTest extends TestCase yield ['import__controller.xml']; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /The routing file "[^"]*" must not specify both the "controller" attribute and the defaults key "_controller" for the "import" tag/ - */ public function testImportWithOverriddenController() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The routing file "[^"]*" must not specify both the "controller" attribute and the defaults key "_controller" for the "import" tag/'); $loader = new XmlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); $loader->load('import_override_defaults.xml'); } diff --git a/lib/symfony/routing/Tests/Loader/YamlFileLoaderTest.php b/lib/symfony/routing/Tests/Loader/YamlFileLoaderTest.php index 4944e5b63..2e3261a1c 100644 --- a/lib/symfony/routing/Tests/Loader/YamlFileLoaderTest.php +++ b/lib/symfony/routing/Tests/Loader/YamlFileLoaderTest.php @@ -41,11 +41,11 @@ class YamlFileLoaderTest extends TestCase } /** - * @expectedException \InvalidArgumentException * @dataProvider getPathsToInvalidFiles */ public function testLoadThrowsExceptionWithInvalidFile($filePath) { + $this->expectException('InvalidArgumentException'); $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures'])); $loader->load($filePath); } @@ -139,12 +139,10 @@ class YamlFileLoaderTest extends TestCase $this->assertSame('AppBundle:Blog:list', $route->getDefault('_controller')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /The routing file "[^"]*" must not specify both the "controller" key and the defaults key "_controller" for "app_blog"/ - */ public function testOverrideControllerInDefaults() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The routing file "[^"]*" must not specify both the "controller" key and the defaults key "_controller" for "app_blog"/'); $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); $loader->load('override_defaults.yml'); } @@ -173,12 +171,10 @@ class YamlFileLoaderTest extends TestCase yield ['import__controller.yml']; } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessageRegExp /The routing file "[^"]*" must not specify both the "controller" key and the defaults key "_controller" for "_static"/ - */ public function testImportWithOverriddenController() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessageRegExp('/The routing file "[^"]*" must not specify both the "controller" key and the defaults key "_controller" for "_static"/'); $loader = new YamlFileLoader(new FileLocator([__DIR__.'/../Fixtures/controller'])); $loader->load('import_override_defaults.yml'); } diff --git a/lib/symfony/routing/Tests/Matcher/DumpedUrlMatcherTest.php b/lib/symfony/routing/Tests/Matcher/DumpedUrlMatcherTest.php index 34946f3f2..873b45a5a 100644 --- a/lib/symfony/routing/Tests/Matcher/DumpedUrlMatcherTest.php +++ b/lib/symfony/routing/Tests/Matcher/DumpedUrlMatcherTest.php @@ -17,21 +17,17 @@ use Symfony\Component\Routing\RouteCollection; class DumpedUrlMatcherTest extends UrlMatcherTest { - /** - * @expectedException \LogicException - * @expectedExceptionMessage The "schemes" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface. - */ public function testSchemeRequirement() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('The "schemes" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.'); parent::testSchemeRequirement(); } - /** - * @expectedException \LogicException - * @expectedExceptionMessage The "schemes" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface. - */ public function testSchemeAndMethodMismatch() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('The "schemes" requirement is only supported for URL matchers that implement RedirectableUrlMatcherInterface.'); parent::testSchemeRequirement(); } diff --git a/lib/symfony/routing/Tests/Matcher/Dumper/PhpMatcherDumperTest.php b/lib/symfony/routing/Tests/Matcher/Dumper/PhpMatcherDumperTest.php index 2816567c1..728601015 100644 --- a/lib/symfony/routing/Tests/Matcher/Dumper/PhpMatcherDumperTest.php +++ b/lib/symfony/routing/Tests/Matcher/Dumper/PhpMatcherDumperTest.php @@ -46,11 +46,9 @@ class PhpMatcherDumperTest extends TestCase @unlink($this->dumpPath); } - /** - * @expectedException \LogicException - */ public function testDumpWhenSchemeIsUsedWithoutAProperDumper() { + $this->expectException('LogicException'); $collection = new RouteCollection(); $collection->add('secure', new Route( '/secure', diff --git a/lib/symfony/routing/Tests/Matcher/RedirectableUrlMatcherTest.php b/lib/symfony/routing/Tests/Matcher/RedirectableUrlMatcherTest.php index b14fe98d4..66b199ab0 100644 --- a/lib/symfony/routing/Tests/Matcher/RedirectableUrlMatcherTest.php +++ b/lib/symfony/routing/Tests/Matcher/RedirectableUrlMatcherTest.php @@ -27,11 +27,9 @@ class RedirectableUrlMatcherTest extends UrlMatcherTest $matcher->match('/foo'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testRedirectWhenNoSlashForNonSafeMethod() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo/')); diff --git a/lib/symfony/routing/Tests/Matcher/TraceableUrlMatcherTest.php b/lib/symfony/routing/Tests/Matcher/TraceableUrlMatcherTest.php index 04ddf845f..b31f99e0c 100644 --- a/lib/symfony/routing/Tests/Matcher/TraceableUrlMatcherTest.php +++ b/lib/symfony/routing/Tests/Matcher/TraceableUrlMatcherTest.php @@ -11,14 +11,13 @@ namespace Symfony\Component\Routing\Tests\Matcher; -use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Matcher\TraceableUrlMatcher; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; -class TraceableUrlMatcherTest extends TestCase +class TraceableUrlMatcherTest extends UrlMatcherTest { public function test() { @@ -119,4 +118,9 @@ class TraceableUrlMatcherTest extends TestCase $traces = $matcher->getTracesForRequest($matchingRequest); $this->assertEquals('Route matches!', $traces[0]['log']); } + + protected function getUrlMatcher(RouteCollection $routes, RequestContext $context = null) + { + return new TraceableUrlMatcher($routes, $context ?: new RequestContext()); + } } diff --git a/lib/symfony/routing/Tests/Matcher/UrlMatcherTest.php b/lib/symfony/routing/Tests/Matcher/UrlMatcherTest.php index 61f9be335..8a9731f98 100644 --- a/lib/symfony/routing/Tests/Matcher/UrlMatcherTest.php +++ b/lib/symfony/routing/Tests/Matcher/UrlMatcherTest.php @@ -27,7 +27,7 @@ class UrlMatcherTest extends TestCase $coll->add('foo', new Route('/foo')); $matcher = $this->getUrlMatcher($coll); - $this->assertInternalType('array', $matcher->match('/foo')); + $this->assertIsArray($matcher->match('/foo')); } public function testMethodNotAllowed() @@ -66,7 +66,7 @@ class UrlMatcherTest extends TestCase $coll->add('foo', new Route('/foo', [], [], [], '', [], ['get'])); $matcher = $this->getUrlMatcher($coll, new RequestContext('', 'head')); - $this->assertInternalType('array', $matcher->match('/foo')); + $this->assertIsArray($matcher->match('/foo')); } public function testMethodNotAllowedAggregatesAllowedMethods() @@ -108,7 +108,7 @@ class UrlMatcherTest extends TestCase $collection = new RouteCollection(); $collection->add('foo', new Route('/foo', [], [], [], '', [], ['get', 'head'])); $matcher = $this->getUrlMatcher($collection); - $this->assertInternalType('array', $matcher->match('/foo')); + $this->assertIsArray($matcher->match('/foo')); // route does not match with POST method context $matcher = $this->getUrlMatcher($collection, new RequestContext('', 'post')); @@ -120,9 +120,9 @@ class UrlMatcherTest extends TestCase // route does match with GET or HEAD method context $matcher = $this->getUrlMatcher($collection); - $this->assertInternalType('array', $matcher->match('/foo')); + $this->assertIsArray($matcher->match('/foo')); $matcher = $this->getUrlMatcher($collection, new RequestContext('', 'head')); - $this->assertInternalType('array', $matcher->match('/foo')); + $this->assertIsArray($matcher->match('/foo')); // route with an optional variable as the first segment $collection = new RouteCollection(); @@ -177,11 +177,9 @@ class UrlMatcherTest extends TestCase $this->assertEquals(['_route' => '$péß^a|'], $matcher->match('/bar')); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testTrailingEncodedNewlineIsNotOverlooked() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $collection = new RouteCollection(); $collection->add('foo', new Route('/foo')); @@ -222,7 +220,7 @@ class UrlMatcherTest extends TestCase $matcher = $this->getUrlMatcher($collection); $this->assertEquals(['_route' => 'foo'], $matcher->match('/foo1')); - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\Routing\Exception\ResourceNotFoundException'); + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $this->assertEquals([], $matcher->match('/foo')); } @@ -279,7 +277,7 @@ class UrlMatcherTest extends TestCase // z and _format are optional. $this->assertEquals(['w' => 'wwwww', 'x' => 'x', 'y' => 'y', 'z' => 'default-z', '_format' => 'html', '_route' => 'test'], $matcher->match('/wwwwwxy')); - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\Routing\Exception\ResourceNotFoundException'); + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $matcher->match('/wxy.html'); } @@ -294,7 +292,7 @@ class UrlMatcherTest extends TestCase // Usually the character in front of an optional parameter can be left out, e.g. with pattern '/get/{what}' just '/get' would match. // But here the 't' in 'get' is not a separating character, so it makes no sense to match without it. - $this->{method_exists($this, $_ = 'expectException') ? $_ : 'setExpectedException'}('Symfony\Component\Routing\Exception\ResourceNotFoundException'); + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $matcher->match('/ge'); } @@ -316,11 +314,9 @@ class UrlMatcherTest extends TestCase $this->assertEquals(['page' => 'index', '_format' => 'mobile.html', '_route' => 'test'], $matcher->match('/index.mobile.html')); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testDefaultRequirementOfVariableDisallowsSlash() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('test', new Route('/{page}.{_format}')); $matcher = $this->getUrlMatcher($coll); @@ -328,11 +324,9 @@ class UrlMatcherTest extends TestCase $matcher->match('/index.sl/ash'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testDefaultRequirementOfVariableDisallowsNextSeparator() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('test', new Route('/{page}.{_format}', [], ['_format' => 'html|xml'])); $matcher = $this->getUrlMatcher($coll); @@ -340,22 +334,18 @@ class UrlMatcherTest extends TestCase $matcher->match('/do.t.html'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testSchemeRequirement() { + $this->getExpectedException() ?: $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo', [], [], [], '', ['https'])); $matcher = $this->getUrlMatcher($coll); $matcher->match('/foo'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testCondition() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $route = new Route('/foo'); $route->setCondition('context.getMethod() == "POST"'); @@ -422,11 +412,9 @@ class UrlMatcherTest extends TestCase $this->assertEquals(['foo' => 'bar', '_route' => 'bar', 'locale' => 'en'], $matcher->match('/bar/bar')); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testWithOutHostHostDoesNotMatch() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/foo/{foo}', [], [], [], '{locale}.example.com')); @@ -434,11 +422,9 @@ class UrlMatcherTest extends TestCase $matcher->match('/foo/bar'); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testPathIsCaseSensitive() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/locale', [], ['locale' => 'EN|FR|DE'])); @@ -455,11 +441,9 @@ class UrlMatcherTest extends TestCase $this->assertEquals(['_route' => 'foo', 'locale' => 'en'], $matcher->match('/')); } - /** - * @expectedException \Symfony\Component\Routing\Exception\NoConfigurationException - */ public function testNoConfiguration() { + $this->expectException('Symfony\Component\Routing\Exception\NoConfigurationException'); $coll = new RouteCollection(); $matcher = $this->getUrlMatcher($coll); @@ -490,11 +474,9 @@ class UrlMatcherTest extends TestCase $this->assertEquals(['_route' => 'buz'], $matcher->match('/prefix/buz')); } - /** - * @expectedException \Symfony\Component\Routing\Exception\ResourceNotFoundException - */ public function testSchemeAndMethodMismatch() { + $this->expectException('Symfony\Component\Routing\Exception\ResourceNotFoundException'); $coll = new RouteCollection(); $coll->add('foo', new Route('/', [], [], [], null, ['https'], ['POST'])); diff --git a/lib/symfony/routing/Tests/RouteCollectionBuilderTest.php b/lib/symfony/routing/Tests/RouteCollectionBuilderTest.php index 11d9453e0..f5042749e 100644 --- a/lib/symfony/routing/Tests/RouteCollectionBuilderTest.php +++ b/lib/symfony/routing/Tests/RouteCollectionBuilderTest.php @@ -75,11 +75,9 @@ class RouteCollectionBuilderTest extends TestCase $this->assertCount(1, $routeCollection->getResources()); } - /** - * @expectedException \BadMethodCallException - */ public function testImportWithoutLoaderThrowsException() { + $this->expectException('BadMethodCallException'); $collectionBuilder = new RouteCollectionBuilder(); $collectionBuilder->import('routing.yml'); } diff --git a/lib/symfony/routing/Tests/RouteCompilerTest.php b/lib/symfony/routing/Tests/RouteCompilerTest.php index d9783147b..b398b2f35 100644 --- a/lib/symfony/routing/Tests/RouteCompilerTest.php +++ b/lib/symfony/routing/Tests/RouteCompilerTest.php @@ -243,52 +243,44 @@ class RouteCompilerTest extends TestCase ]; } - /** - * @expectedException \LogicException - */ public function testRouteWithSameVariableTwice() { + $this->expectException('LogicException'); $route = new Route('/{name}/{name}'); - $compiled = $route->compile(); + $route->compile(); } - /** - * @expectedException \LogicException - */ public function testRouteCharsetMismatch() { + $this->expectException('LogicException'); $route = new Route("/\xE9/{bar}", [], ['bar' => '.'], ['utf8' => true]); - $compiled = $route->compile(); + $route->compile(); } - /** - * @expectedException \LogicException - */ public function testRequirementCharsetMismatch() { + $this->expectException('LogicException'); $route = new Route('/foo/{bar}', [], ['bar' => "\xE9"], ['utf8' => true]); - $compiled = $route->compile(); + $route->compile(); } - /** - * @expectedException \InvalidArgumentException - */ public function testRouteWithFragmentAsPathParameter() { + $this->expectException('InvalidArgumentException'); $route = new Route('/{_fragment}'); - $compiled = $route->compile(); + $route->compile(); } /** * @dataProvider getVariableNamesStartingWithADigit - * @expectedException \DomainException */ public function testRouteWithVariableNameStartingWithADigit($name) { + $this->expectException('DomainException'); $route = new Route('/{'.$name.'}'); $route->compile(); } @@ -373,11 +365,9 @@ class RouteCompilerTest extends TestCase ]; } - /** - * @expectedException \DomainException - */ public function testRouteWithTooLongVariableName() { + $this->expectException('DomainException'); $route = new Route(sprintf('/{%s}', str_repeat('a', RouteCompiler::VARIABLE_MAXIMUM_LENGTH + 1))); $route->compile(); } diff --git a/lib/symfony/routing/Tests/RouteTest.php b/lib/symfony/routing/Tests/RouteTest.php index 179f4880d..53ae859df 100644 --- a/lib/symfony/routing/Tests/RouteTest.php +++ b/lib/symfony/routing/Tests/RouteTest.php @@ -124,10 +124,10 @@ class RouteTest extends TestCase /** * @dataProvider getInvalidRequirements - * @expectedException \InvalidArgumentException */ public function testSetInvalidRequirement($req) { + $this->expectException('InvalidArgumentException'); $route = new Route('/{foo}'); $route->setRequirement('foo', $req); } diff --git a/lib/symfony/routing/Tests/RouterTest.php b/lib/symfony/routing/Tests/RouterTest.php index 0f46e5317..fc5e633b0 100644 --- a/lib/symfony/routing/Tests/RouterTest.php +++ b/lib/symfony/routing/Tests/RouterTest.php @@ -41,12 +41,10 @@ class RouterTest extends TestCase $this->assertSame('ResourceType', $this->router->getOption('resource_type')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The Router does not support the following options: "option_foo", "option_bar" - */ public function testSetOptionsWithUnsupportedOptions() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The Router does not support the following options: "option_foo", "option_bar"'); $this->router->setOptions([ 'cache_dir' => './cache', 'option_foo' => true, @@ -62,21 +60,17 @@ class RouterTest extends TestCase $this->assertSame('./cache', $this->router->getOption('cache_dir')); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The Router does not support the "option_foo" option - */ public function testSetOptionWithUnsupportedOption() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The Router does not support the "option_foo" option'); $this->router->setOption('option_foo', true); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The Router does not support the "option_foo" option - */ public function testGetOptionWithUnsupportedOption() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The Router does not support the "option_foo" option'); $this->router->getOption('option_foo', true); } diff --git a/lib/symfony/stopwatch/Section.php b/lib/symfony/stopwatch/Section.php index 14fba8b58..f0c5e8b44 100644 --- a/lib/symfony/stopwatch/Section.php +++ b/lib/symfony/stopwatch/Section.php @@ -67,6 +67,8 @@ class Section return $child; } } + + return null; } /** @@ -110,8 +112,8 @@ class Section /** * Starts an event. * - * @param string $name The event name - * @param string $category The event category + * @param string $name The event name + * @param string|null $category The event category * * @return StopwatchEvent The event */ diff --git a/lib/symfony/stopwatch/StopwatchEvent.php b/lib/symfony/stopwatch/StopwatchEvent.php index bc8c6b5f4..e6739469d 100644 --- a/lib/symfony/stopwatch/StopwatchEvent.php +++ b/lib/symfony/stopwatch/StopwatchEvent.php @@ -154,7 +154,15 @@ class StopwatchEvent */ public function getStartTime() { - return isset($this->periods[0]) ? $this->periods[0]->getStartTime() : 0; + if (isset($this->periods[0])) { + return $this->periods[0]->getStartTime(); + } + + if ($this->started) { + return $this->started[0]; + } + + return 0; } /** @@ -177,12 +185,10 @@ class StopwatchEvent public function getDuration() { $periods = $this->periods; - $stopped = \count($periods); - $left = \count($this->started) - $stopped; + $left = \count($this->started); - for ($i = 0; $i < $left; ++$i) { - $index = $stopped + $i; - $periods[] = new StopwatchPeriod($this->started[$index], $this->getNow(), $this->morePrecision); + for ($i = $left - 1; $i >= 0; --$i) { + $periods[] = new StopwatchPeriod($this->started[$i], $this->getNow(), $this->morePrecision); } $total = 0; diff --git a/lib/symfony/stopwatch/Tests/StopwatchEventTest.php b/lib/symfony/stopwatch/Tests/StopwatchEventTest.php index 415ab3e9d..349334db7 100644 --- a/lib/symfony/stopwatch/Tests/StopwatchEventTest.php +++ b/lib/symfony/stopwatch/Tests/StopwatchEventTest.php @@ -73,7 +73,7 @@ class StopwatchEventTest extends TestCase $event->start(); usleep(200000); $event->stop(); - $this->assertEquals(200, $event->getDuration(), '', self::DELTA); + $this->assertEqualsWithDelta(200, $event->getDuration(), self::DELTA); $event = new StopwatchEvent(microtime(true) * 1000); $event->start(); @@ -83,7 +83,7 @@ class StopwatchEventTest extends TestCase $event->start(); usleep(100000); $event->stop(); - $this->assertEquals(200, $event->getDuration(), '', self::DELTA); + $this->assertEqualsWithDelta(200, $event->getDuration(), self::DELTA); } public function testDurationBeforeStop() @@ -91,7 +91,7 @@ class StopwatchEventTest extends TestCase $event = new StopwatchEvent(microtime(true) * 1000); $event->start(); usleep(200000); - $this->assertEquals(200, $event->getDuration(), '', self::DELTA); + $this->assertEqualsWithDelta(200, $event->getDuration(), self::DELTA); $event = new StopwatchEvent(microtime(true) * 1000); $event->start(); @@ -99,15 +99,30 @@ class StopwatchEventTest extends TestCase $event->stop(); usleep(50000); $event->start(); + $this->assertEqualsWithDelta(100, $event->getDuration(), self::DELTA); usleep(100000); - $this->assertEquals(100, $event->getDuration(), '', self::DELTA); + $this->assertEqualsWithDelta(200, $event->getDuration(), self::DELTA); + } + + public function testDurationWithMultipleStarts() + { + $event = new StopwatchEvent(microtime(true) * 1000); + $event->start(); + usleep(100000); + $event->start(); + usleep(100000); + $this->assertEqualsWithDelta(300, $event->getDuration(), self::DELTA); + $event->stop(); + $this->assertEqualsWithDelta(300, $event->getDuration(), self::DELTA); + usleep(100000); + $this->assertEqualsWithDelta(400, $event->getDuration(), self::DELTA); + $event->stop(); + $this->assertEqualsWithDelta(400, $event->getDuration(), self::DELTA); } - /** - * @expectedException \LogicException - */ public function testStopWithoutStart() { + $this->expectException('LogicException'); $event = new StopwatchEvent(microtime(true) * 1000); $event->stop(); } @@ -134,7 +149,7 @@ class StopwatchEventTest extends TestCase $event->start(); usleep(100000); $event->ensureStopped(); - $this->assertEquals(300, $event->getDuration(), '', self::DELTA); + $this->assertEqualsWithDelta(300, $event->getDuration(), self::DELTA); } public function testStartTime() @@ -151,14 +166,33 @@ class StopwatchEventTest extends TestCase $event->start(); usleep(100000); $event->stop(); - $this->assertEquals(0, $event->getStartTime(), '', self::DELTA); + $this->assertEqualsWithDelta(0, $event->getStartTime(), self::DELTA); + } + + public function testStartTimeWhenStartedLater() + { + $event = new StopwatchEvent(microtime(true) * 1000); + usleep(100000); + $this->assertLessThanOrEqual(0.5, $event->getStartTime()); + + $event = new StopwatchEvent(microtime(true) * 1000); + usleep(100000); + $event->start(); + $event->stop(); + $this->assertLessThanOrEqual(101, $event->getStartTime()); + + $event = new StopwatchEvent(microtime(true) * 1000); + usleep(100000); + $event->start(); + usleep(100000); + $this->assertEqualsWithDelta(100, $event->getStartTime(), self::DELTA); + $event->stop(); + $this->assertEqualsWithDelta(100, $event->getStartTime(), self::DELTA); } - /** - * @expectedException \InvalidArgumentException - */ public function testInvalidOriginThrowsAnException() { + $this->expectException('InvalidArgumentException'); new StopwatchEvent('abc'); } diff --git a/lib/symfony/stopwatch/Tests/StopwatchTest.php b/lib/symfony/stopwatch/Tests/StopwatchTest.php index 30f976ad0..b8efa373b 100644 --- a/lib/symfony/stopwatch/Tests/StopwatchTest.php +++ b/lib/symfony/stopwatch/Tests/StopwatchTest.php @@ -87,23 +87,19 @@ class StopwatchTest extends TestCase $event = $stopwatch->stop('foo'); $this->assertInstanceOf('Symfony\Component\Stopwatch\StopwatchEvent', $event); - $this->assertEquals(200, $event->getDuration(), '', self::DELTA); + $this->assertEqualsWithDelta(200, $event->getDuration(), self::DELTA); } - /** - * @expectedException \LogicException - */ public function testUnknownEvent() { + $this->expectException('LogicException'); $stopwatch = new Stopwatch(); $stopwatch->getEvent('foo'); } - /** - * @expectedException \LogicException - */ public function testStopWithoutStart() { + $this->expectException('LogicException'); $stopwatch = new Stopwatch(); $stopwatch->stop('foo'); } @@ -115,9 +111,9 @@ class StopwatchTest extends TestCase $stopwatch->start('foo'); $event = $stopwatch->stop('foo'); - $this->assertInternalType('float', $event->getStartTime()); - $this->assertInternalType('float', $event->getEndTime()); - $this->assertInternalType('float', $event->getDuration()); + $this->assertIsFloat($event->getStartTime()); + $this->assertIsFloat($event->getEndTime()); + $this->assertIsFloat($event->getDuration()); } public function testSection() @@ -165,11 +161,9 @@ class StopwatchTest extends TestCase $this->assertCount(2, $events['__section__']->getPeriods()); } - /** - * @expectedException \LogicException - */ public function testReopenANewSectionShouldThrowAnException() { + $this->expectException('LogicException'); $stopwatch = new Stopwatch(); $stopwatch->openSection('section'); } diff --git a/lib/symfony/twig-bridge/AppVariable.php b/lib/symfony/twig-bridge/AppVariable.php index 21020270a..eb9cec6dd 100644 --- a/lib/symfony/twig-bridge/AppVariable.php +++ b/lib/symfony/twig-bridge/AppVariable.php @@ -68,7 +68,7 @@ class AppVariable /** * Returns the current user. * - * @return mixed + * @return object|null * * @see TokenInterface::getUser() */ @@ -79,13 +79,12 @@ class AppVariable } if (!$token = $tokenStorage->getToken()) { - return; + return null; } $user = $token->getUser(); - if (\is_object($user)) { - return $user; - } + + return \is_object($user) ? $user : null; } /** @@ -113,9 +112,7 @@ class AppVariable throw new \RuntimeException('The "app.session" variable is not available.'); } - if ($request = $this->getRequest()) { - return $request->getSession(); - } + return ($request = $this->getRequest()) ? $request->getSession() : null; } /** diff --git a/lib/symfony/twig-bridge/Command/DebugCommand.php b/lib/symfony/twig-bridge/Command/DebugCommand.php index 618dce76c..b45b580ee 100644 --- a/lib/symfony/twig-bridge/Command/DebugCommand.php +++ b/lib/symfony/twig-bridge/Command/DebugCommand.php @@ -220,16 +220,16 @@ EOF return $entity; } if ('tests' === $type) { - return; + return null; } if ('functions' === $type || 'filters' === $type) { $cb = $entity->getCallable(); if (null === $cb) { - return; + return null; } if (\is_array($cb)) { if (!method_exists($cb[0], $cb[1])) { - return; + return null; } $refl = new \ReflectionMethod($cb[0], $cb[1]); } elseif (\is_object($cb) && method_exists($cb, '__invoke')) { @@ -268,6 +268,8 @@ EOF return $args; } + + return null; } private function getPrettyMetadata($type, $entity, $decorated) @@ -302,5 +304,7 @@ EOF if ('filters' === $type) { return $meta ? '('.implode(', ', $meta).')' : ''; } + + return null; } } diff --git a/lib/symfony/twig-bridge/Extension/CodeExtension.php b/lib/symfony/twig-bridge/Extension/CodeExtension.php index 55855427e..717d4de69 100644 --- a/lib/symfony/twig-bridge/Extension/CodeExtension.php +++ b/lib/symfony/twig-bridge/Extension/CodeExtension.php @@ -136,7 +136,7 @@ class CodeExtension extends AbstractExtension { if (is_file($file) && is_readable($file)) { // highlight_file could throw warnings - // see https://bugs.php.net/bug.php?id=25725 + // see https://bugs.php.net/25725 $code = @highlight_file($file, true); // remove main code/span tags $code = preg_replace('#^\s*(.*)\s*#s', '\\1', $code); diff --git a/lib/symfony/twig-bridge/Extension/DumpExtension.php b/lib/symfony/twig-bridge/Extension/DumpExtension.php index 88b75368d..2be105623 100644 --- a/lib/symfony/twig-bridge/Extension/DumpExtension.php +++ b/lib/symfony/twig-bridge/Extension/DumpExtension.php @@ -55,7 +55,7 @@ class DumpExtension extends AbstractExtension public function dump(Environment $env, $context) { if (!$env->isDebug()) { - return; + return null; } if (2 === \func_num_args()) { diff --git a/lib/symfony/twig-bridge/Extension/RoutingExtension.php b/lib/symfony/twig-bridge/Extension/RoutingExtension.php index f380d13a5..936c2d998 100644 --- a/lib/symfony/twig-bridge/Extension/RoutingExtension.php +++ b/lib/symfony/twig-bridge/Extension/RoutingExtension.php @@ -33,9 +33,7 @@ class RoutingExtension extends AbstractExtension } /** - * Returns a list of functions to add to the existing list. - * - * @return array An array of functions + * {@inheritdoc} */ public function getFunctions() { diff --git a/lib/symfony/twig-bridge/Node/SearchAndRenderBlockNode.php b/lib/symfony/twig-bridge/Node/SearchAndRenderBlockNode.php index 612bec14e..8925d5887 100644 --- a/lib/symfony/twig-bridge/Node/SearchAndRenderBlockNode.php +++ b/lib/symfony/twig-bridge/Node/SearchAndRenderBlockNode.php @@ -28,7 +28,6 @@ class SearchAndRenderBlockNode extends FunctionExpression preg_match('/_([^_]+)$/', $this->getAttribute('name'), $matches); - $label = null; $arguments = iterator_to_array($this->getNode('arguments')); $blockNameSuffix = $matches[1]; diff --git a/lib/symfony/twig-bridge/NodeVisitor/TranslationDefaultDomainNodeVisitor.php b/lib/symfony/twig-bridge/NodeVisitor/TranslationDefaultDomainNodeVisitor.php index 04b68ef6b..be08d0d1d 100644 --- a/lib/symfony/twig-bridge/NodeVisitor/TranslationDefaultDomainNodeVisitor.php +++ b/lib/symfony/twig-bridge/NodeVisitor/TranslationDefaultDomainNodeVisitor.php @@ -107,6 +107,8 @@ class TranslationDefaultDomainNodeVisitor extends AbstractNodeVisitor /** * {@inheritdoc} + * + * @return int */ public function getPriority() { diff --git a/lib/symfony/twig-bridge/NodeVisitor/TranslationNodeVisitor.php b/lib/symfony/twig-bridge/NodeVisitor/TranslationNodeVisitor.php index 2585b4823..1a399ce8b 100644 --- a/lib/symfony/twig-bridge/NodeVisitor/TranslationNodeVisitor.php +++ b/lib/symfony/twig-bridge/NodeVisitor/TranslationNodeVisitor.php @@ -97,6 +97,8 @@ class TranslationNodeVisitor extends AbstractNodeVisitor /** * {@inheritdoc} + * + * @return int */ public function getPriority() { @@ -104,8 +106,7 @@ class TranslationNodeVisitor extends AbstractNodeVisitor } /** - * @param Node $arguments - * @param int $index + * @param int $index * * @return string|null */ @@ -116,7 +117,7 @@ class TranslationNodeVisitor extends AbstractNodeVisitor } elseif ($arguments->hasNode($index)) { $argument = $arguments->getNode($index); } else { - return; + return null; } return $this->getReadDomainFromNode($argument); diff --git a/lib/symfony/twig-bridge/Resources/views/Form/bootstrap_4_horizontal_layout.html.twig b/lib/symfony/twig-bridge/Resources/views/Form/bootstrap_4_horizontal_layout.html.twig index e23e6f8a2..5673cf212 100644 --- a/lib/symfony/twig-bridge/Resources/views/Form/bootstrap_4_horizontal_layout.html.twig +++ b/lib/symfony/twig-bridge/Resources/views/Form/bootstrap_4_horizontal_layout.html.twig @@ -71,7 +71,6 @@ col-sm-10
{#--#}
{{- form_widget(form) -}} - {{- form_errors(form) -}}
{#--#}
{%- endblock checkbox_row %} diff --git a/lib/symfony/twig-bridge/Tests/AppVariableTest.php b/lib/symfony/twig-bridge/Tests/AppVariableTest.php index 0502a64ce..eb132e720 100644 --- a/lib/symfony/twig-bridge/Tests/AppVariableTest.php +++ b/lib/symfony/twig-bridge/Tests/AppVariableTest.php @@ -114,51 +114,39 @@ class AppVariableTest extends TestCase $this->assertNull($this->appVariable->getUser()); } - /** - * @expectedException \RuntimeException - */ public function testEnvironmentNotSet() { + $this->expectException('RuntimeException'); $this->appVariable->getEnvironment(); } - /** - * @expectedException \RuntimeException - */ public function testDebugNotSet() { + $this->expectException('RuntimeException'); $this->appVariable->getDebug(); } - /** - * @expectedException \RuntimeException - */ public function testGetTokenWithTokenStorageNotSet() { + $this->expectException('RuntimeException'); $this->appVariable->getToken(); } - /** - * @expectedException \RuntimeException - */ public function testGetUserWithTokenStorageNotSet() { + $this->expectException('RuntimeException'); $this->appVariable->getUser(); } - /** - * @expectedException \RuntimeException - */ public function testGetRequestWithRequestStackNotSet() { + $this->expectException('RuntimeException'); $this->appVariable->getRequest(); } - /** - * @expectedException \RuntimeException - */ public function testGetSessionWithRequestStackNotSet() { + $this->expectException('RuntimeException'); $this->appVariable->getSession(); } @@ -192,10 +180,10 @@ class AppVariableTest extends TestCase $flashMessages = $this->setFlashMessages(); $this->assertEquals($flashMessages, $this->appVariable->getFlashes([])); - $flashMessages = $this->setFlashMessages(); + $this->setFlashMessages(); $this->assertEquals([], $this->appVariable->getFlashes('this-does-not-exist')); - $flashMessages = $this->setFlashMessages(); + $this->setFlashMessages(); $this->assertEquals( ['this-does-not-exist' => []], $this->appVariable->getFlashes(['this-does-not-exist']) diff --git a/lib/symfony/twig-bridge/Tests/Command/DebugCommandTest.php b/lib/symfony/twig-bridge/Tests/Command/DebugCommandTest.php index 2f4cc9cd8..7eb96018a 100644 --- a/lib/symfony/twig-bridge/Tests/Command/DebugCommandTest.php +++ b/lib/symfony/twig-bridge/Tests/Command/DebugCommandTest.php @@ -26,7 +26,7 @@ class DebugCommandTest extends TestCase $ret = $tester->execute([], ['decorated' => false]); $this->assertEquals(0, $ret, 'Returns 0 in case of success'); - $this->assertContains('Functions', trim($tester->getDisplay())); + $this->assertStringContainsString('Functions', trim($tester->getDisplay())); } public function testLineSeparatorInLoaderPaths() @@ -59,7 +59,7 @@ Loader Paths TXT; $this->assertEquals(0, $ret, 'Returns 0 in case of success'); - $this->assertContains($loaderPaths, trim($tester->getDisplay(true))); + $this->assertStringContainsString($loaderPaths, trim($tester->getDisplay(true))); } public function testWithGlobals() @@ -70,7 +70,7 @@ TXT; $display = $tester->getDisplay(); - $this->assertContains(json_encode($message), $display); + $this->assertStringContainsString(json_encode($message), $display); } public function testWithGlobalsJson() diff --git a/lib/symfony/twig-bridge/Tests/Command/LintCommandTest.php b/lib/symfony/twig-bridge/Tests/Command/LintCommandTest.php index e50a555e7..84154512b 100644 --- a/lib/symfony/twig-bridge/Tests/Command/LintCommandTest.php +++ b/lib/symfony/twig-bridge/Tests/Command/LintCommandTest.php @@ -31,7 +31,7 @@ class LintCommandTest extends TestCase $ret = $tester->execute(['filename' => [$filename]], ['verbosity' => OutputInterface::VERBOSITY_VERBOSE, 'decorated' => false]); $this->assertEquals(0, $ret, 'Returns 0 in case of success'); - $this->assertContains('OK in', trim($tester->getDisplay())); + $this->assertStringContainsString('OK in', trim($tester->getDisplay())); } public function testLintIncorrectFile() @@ -45,16 +45,14 @@ class LintCommandTest extends TestCase $this->assertRegExp('/ERROR in \S+ \(line /', trim($tester->getDisplay())); } - /** - * @expectedException \RuntimeException - */ public function testLintFileNotReadable() { + $this->expectException('RuntimeException'); $tester = $this->createCommandTester(); $filename = $this->createFile(''); unlink($filename); - $ret = $tester->execute(['filename' => [$filename]], ['decorated' => false]); + $tester->execute(['filename' => [$filename]], ['decorated' => false]); } public function testLintFileCompileTimeException() @@ -71,11 +69,11 @@ class LintCommandTest extends TestCase /** * @group legacy * @expectedDeprecation Passing a command name as the first argument of "Symfony\Bridge\Twig\Command\LintCommand::__construct()" is deprecated since Symfony 3.4 and support for it will be removed in 4.0. If the command was registered by convention, make it a service instead. - * @expectedException \RuntimeException - * @expectedExceptionMessage The Twig environment needs to be set. */ public function testLegacyLintCommand() { + $this->expectException('RuntimeException'); + $this->expectExceptionMessage('The Twig environment needs to be set.'); $command = new LintCommand(); $application = new Application(); diff --git a/lib/symfony/twig-bridge/Tests/Extension/AbstractBootstrap3LayoutTest.php b/lib/symfony/twig-bridge/Tests/Extension/AbstractBootstrap3LayoutTest.php index 5763345af..f04372c54 100644 --- a/lib/symfony/twig-bridge/Tests/Extension/AbstractBootstrap3LayoutTest.php +++ b/lib/symfony/twig-bridge/Tests/Extension/AbstractBootstrap3LayoutTest.php @@ -2396,7 +2396,7 @@ abstract class AbstractBootstrap3LayoutTest extends AbstractLayoutTest public function testUrlWithDefaultProtocol() { - $url = 'http://www.google.com?foo1=bar1&foo2=bar2'; + $url = 'http://www.example.com?foo1=bar1&foo2=bar2'; $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\UrlType', $url, ['default_protocol' => 'http']); $this->assertWidgetMatchesXpath($form->createView(), ['attr' => ['class' => 'my&class']], @@ -2404,7 +2404,7 @@ abstract class AbstractBootstrap3LayoutTest extends AbstractLayoutTest [@type="text"] [@name="name"] [@class="my&class form-control"] - [@value="http://www.google.com?foo1=bar1&foo2=bar2"] + [@value="http://www.example.com?foo1=bar1&foo2=bar2"] [@inputmode="url"] ' ); @@ -2412,7 +2412,7 @@ abstract class AbstractBootstrap3LayoutTest extends AbstractLayoutTest public function testUrlWithoutDefaultProtocol() { - $url = 'http://www.google.com?foo1=bar1&foo2=bar2'; + $url = 'http://www.example.com?foo1=bar1&foo2=bar2'; $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\UrlType', $url, ['default_protocol' => null]); $this->assertWidgetMatchesXpath($form->createView(), ['attr' => ['class' => 'my&class']], @@ -2420,7 +2420,7 @@ abstract class AbstractBootstrap3LayoutTest extends AbstractLayoutTest [@type="url"] [@name="name"] [@class="my&class form-control"] - [@value="http://www.google.com?foo1=bar1&foo2=bar2"] + [@value="http://www.example.com?foo1=bar1&foo2=bar2"] ' ); } diff --git a/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php b/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php index 02f6ac9b1..b11d1720b 100644 --- a/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php +++ b/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php @@ -33,10 +33,11 @@ class FormExtensionBootstrap3HorizontalLayoutTest extends AbstractBootstrap3Hori */ private $renderer; - protected function setUp() + /** + * @before + */ + public function doSetUp() { - parent::setUp(); - $loader = new StubFilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', diff --git a/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap3LayoutTest.php b/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap3LayoutTest.php index 0c2ef171b..0bb5a7b6c 100644 --- a/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap3LayoutTest.php +++ b/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap3LayoutTest.php @@ -29,10 +29,11 @@ class FormExtensionBootstrap3LayoutTest extends AbstractBootstrap3LayoutTest */ private $renderer; - protected function setUp() + /** + * @before + */ + public function doSetUp() { - parent::setUp(); - $loader = new StubFilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', diff --git a/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap4HorizontalLayoutTest.php b/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap4HorizontalLayoutTest.php index 319c0e573..02ab01fc5 100644 --- a/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap4HorizontalLayoutTest.php +++ b/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap4HorizontalLayoutTest.php @@ -35,10 +35,11 @@ class FormExtensionBootstrap4HorizontalLayoutTest extends AbstractBootstrap4Hori private $renderer; - protected function setUp() + /** + * @before + */ + public function doSetUp() { - parent::setUp(); - $loader = new StubFilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', diff --git a/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap4LayoutTest.php b/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap4LayoutTest.php index ea36552d8..cb2328b51 100644 --- a/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap4LayoutTest.php +++ b/lib/symfony/twig-bridge/Tests/Extension/FormExtensionBootstrap4LayoutTest.php @@ -33,10 +33,11 @@ class FormExtensionBootstrap4LayoutTest extends AbstractBootstrap4LayoutTest */ private $renderer; - protected function setUp() + /** + * @before + */ + public function doSetUp() { - parent::setUp(); - $loader = new StubFilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', diff --git a/lib/symfony/twig-bridge/Tests/Extension/FormExtensionDivLayoutTest.php b/lib/symfony/twig-bridge/Tests/Extension/FormExtensionDivLayoutTest.php index 214df3c7f..51e587411 100644 --- a/lib/symfony/twig-bridge/Tests/Extension/FormExtensionDivLayoutTest.php +++ b/lib/symfony/twig-bridge/Tests/Extension/FormExtensionDivLayoutTest.php @@ -33,10 +33,11 @@ class FormExtensionDivLayoutTest extends AbstractDivLayoutTest protected static $supportedFeatureSetVersion = 304; - protected function setUp() + /** + * @before + */ + public function doSetUp() { - parent::setUp(); - $loader = new StubFilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', diff --git a/lib/symfony/twig-bridge/Tests/Extension/FormExtensionTableLayoutTest.php b/lib/symfony/twig-bridge/Tests/Extension/FormExtensionTableLayoutTest.php index f95676736..0676dffd5 100644 --- a/lib/symfony/twig-bridge/Tests/Extension/FormExtensionTableLayoutTest.php +++ b/lib/symfony/twig-bridge/Tests/Extension/FormExtensionTableLayoutTest.php @@ -32,10 +32,11 @@ class FormExtensionTableLayoutTest extends AbstractTableLayoutTest protected static $supportedFeatureSetVersion = 304; - protected function setUp() + /** + * @before + */ + public function doSetUp() { - parent::setUp(); - $loader = new StubFilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', diff --git a/lib/symfony/twig-bridge/Tests/Extension/HttpKernelExtensionTest.php b/lib/symfony/twig-bridge/Tests/Extension/HttpKernelExtensionTest.php index 22084ec1a..c635935f3 100644 --- a/lib/symfony/twig-bridge/Tests/Extension/HttpKernelExtensionTest.php +++ b/lib/symfony/twig-bridge/Tests/Extension/HttpKernelExtensionTest.php @@ -22,11 +22,9 @@ use Twig\Loader\ArrayLoader; class HttpKernelExtensionTest extends TestCase { - /** - * @expectedException \Twig\Error\RuntimeError - */ public function testFragmentWithError() { + $this->expectException('Twig\Error\RuntimeError'); $renderer = $this->getFragmentHandler($this->throwException(new \Exception('foo'))); $this->renderTemplate($renderer); @@ -49,12 +47,8 @@ class HttpKernelExtensionTest extends TestCase ; $renderer = new FragmentHandler($context); - if (method_exists($this, 'expectException')) { - $this->expectException('InvalidArgumentException'); - $this->expectExceptionMessage('The "inline" renderer does not exist.'); - } else { - $this->setExpectedException('InvalidArgumentException', 'The "inline" renderer does not exist.'); - } + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The "inline" renderer does not exist.'); $renderer->render('/foo'); } diff --git a/lib/symfony/twig-bridge/Tests/Extension/StopwatchExtensionTest.php b/lib/symfony/twig-bridge/Tests/Extension/StopwatchExtensionTest.php index 1af65e4c1..35f3baa1b 100644 --- a/lib/symfony/twig-bridge/Tests/Extension/StopwatchExtensionTest.php +++ b/lib/symfony/twig-bridge/Tests/Extension/StopwatchExtensionTest.php @@ -19,11 +19,9 @@ use Twig\Loader\ArrayLoader; class StopwatchExtensionTest extends TestCase { - /** - * @expectedException \Twig\Error\SyntaxError - */ public function testFailIfStoppingWrongEvent() { + $this->expectException('Twig\Error\SyntaxError'); $this->testTiming('{% stopwatch "foo" %}{% endstopwatch "bar" %}', []); } @@ -36,7 +34,7 @@ class StopwatchExtensionTest extends TestCase $twig->addExtension(new StopwatchExtension($this->getStopwatch($events))); try { - $nodes = $twig->render('template'); + $twig->render('template'); } catch (RuntimeError $e) { throw $e->getPrevious(); } diff --git a/lib/symfony/twig-bridge/Tests/Extension/TranslationExtensionTest.php b/lib/symfony/twig-bridge/Tests/Extension/TranslationExtensionTest.php index ef4bf9e11..206cda678 100644 --- a/lib/symfony/twig-bridge/Tests/Extension/TranslationExtensionTest.php +++ b/lib/symfony/twig-bridge/Tests/Extension/TranslationExtensionTest.php @@ -45,31 +45,25 @@ class TranslationExtensionTest extends TestCase $this->assertEquals($expected, $this->getTemplate($template)->render($variables)); } - /** - * @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() { - $output = $this->getTemplate("{% trans \n\nfoo %}{% endtrans %}")->render(); + $this->expectException('Twig\Error\SyntaxError'); + $this->expectExceptionMessage('Unexpected token. Twig was looking for the "with", "from", or "into" keyword in "index" at line 3.'); + $this->getTemplate("{% trans \n\nfoo %}{% endtrans %}")->render(); } - /** - * @expectedException \Twig\Error\SyntaxError - * @expectedExceptionMessage A message inside a trans tag must be a simple text in "index" at line 2. - */ public function testTransComplexBody() { - $output = $this->getTemplate("{% trans %}\n{{ 1 + 2 }}{% endtrans %}")->render(); + $this->expectException('Twig\Error\SyntaxError'); + $this->expectExceptionMessage('A message inside a trans tag must be a simple text in "index" at line 2.'); + $this->getTemplate("{% trans %}\n{{ 1 + 2 }}{% endtrans %}")->render(); } - /** - * @expectedException \Twig\Error\SyntaxError - * @expectedExceptionMessage A message inside a transchoice tag must be a simple text in "index" at line 2. - */ public function testTransChoiceComplexBody() { - $output = $this->getTemplate("{% transchoice count %}\n{{ 1 + 2 }}{% endtranschoice %}")->render(); + $this->expectException('Twig\Error\SyntaxError'); + $this->expectExceptionMessage('A message inside a transchoice tag must be a simple text in "index" at line 2.'); + $this->getTemplate("{% transchoice count %}\n{{ 1 + 2 }}{% endtranschoice %}")->render(); } public function getTransTests() diff --git a/lib/symfony/twig-bridge/Tests/TokenParser/FormThemeTokenParserTest.php b/lib/symfony/twig-bridge/Tests/TokenParser/FormThemeTokenParserTest.php index 71180156b..ce1980eb1 100644 --- a/lib/symfony/twig-bridge/Tests/TokenParser/FormThemeTokenParserTest.php +++ b/lib/symfony/twig-bridge/Tests/TokenParser/FormThemeTokenParserTest.php @@ -34,9 +34,7 @@ class FormThemeTokenParserTest extends TestCase $stream = $env->tokenize($source); $parser = new Parser($env); - if (method_exists($expected, 'setSourceContext')) { - $expected->setSourceContext($source); - } + $expected->setSourceContext($source); $this->assertEquals($expected, $parser->parse($stream)->getNode('body')->getNode(0)); } diff --git a/lib/symfony/twig-bridge/Tests/Translation/TwigExtractorTest.php b/lib/symfony/twig-bridge/Tests/Translation/TwigExtractorTest.php index 5dd5bb79d..82d729836 100644 --- a/lib/symfony/twig-bridge/Tests/Translation/TwigExtractorTest.php +++ b/lib/symfony/twig-bridge/Tests/Translation/TwigExtractorTest.php @@ -76,11 +76,11 @@ class TwigExtractorTest extends TestCase } /** - * @expectedException \Twig\Error\Error * @dataProvider resourcesWithSyntaxErrorsProvider */ public function testExtractSyntaxError($resources) { + $this->expectException('Twig\Error\Error'); $twig = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock()); $twig->addExtension(new TranslationExtension($this->getMockBuilder('Symfony\Component\Translation\TranslatorInterface')->getMock())); @@ -89,13 +89,10 @@ class TwigExtractorTest extends TestCase try { $extractor->extract($resources, new MessageCatalogue('en')); } 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()); - $this->assertSame('Unclosed "block".', $e->getMessage()); - } else { - $this->expectExceptionMessageRegExp('/Unclosed "block" in ".*extractor(\\/|\\\\)syntax_error\\.twig" at line 1/'); - } + $this->assertSame(\dirname(__DIR__).strtr('/Fixtures/extractor/syntax_error.twig', '/', \DIRECTORY_SEPARATOR), $e->getFile()); + $this->assertSame(1, $e->getLine()); + $this->assertSame('Unclosed "block".', $e->getMessage()); + throw $e; } } diff --git a/lib/symfony/twig-bridge/Tests/TwigEngineTest.php b/lib/symfony/twig-bridge/Tests/TwigEngineTest.php index ab932eebc..e136d0c76 100644 --- a/lib/symfony/twig-bridge/Tests/TwigEngineTest.php +++ b/lib/symfony/twig-bridge/Tests/TwigEngineTest.php @@ -58,11 +58,9 @@ class TwigEngineTest extends TestCase $this->assertSame('foo', $engine->render(new TemplateReference('index'))); } - /** - * @expectedException \Twig\Error\SyntaxError - */ public function testRenderWithError() { + $this->expectException('Twig\Error\SyntaxError'); $engine = $this->getTwig(); $engine->render(new TemplateReference('error')); diff --git a/lib/symfony/twig-bridge/TokenParser/TransChoiceTokenParser.php b/lib/symfony/twig-bridge/TokenParser/TransChoiceTokenParser.php index 7b673856f..b1c8a39b3 100644 --- a/lib/symfony/twig-bridge/TokenParser/TransChoiceTokenParser.php +++ b/lib/symfony/twig-bridge/TokenParser/TransChoiceTokenParser.php @@ -15,7 +15,6 @@ 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; @@ -27,11 +26,7 @@ use Twig\Token; class TransChoiceTokenParser extends TransTokenParser { /** - * Parses a token and returns a node. - * - * @return Node - * - * @throws SyntaxError + * {@inheritdoc} */ public function parse(Token $token) { @@ -82,9 +77,7 @@ class TransChoiceTokenParser extends TransTokenParser } /** - * Gets the tag name associated with this token parser. - * - * @return string The tag name + * {@inheritdoc} */ public function getTag() { diff --git a/lib/symfony/twig-bridge/TokenParser/TransDefaultDomainTokenParser.php b/lib/symfony/twig-bridge/TokenParser/TransDefaultDomainTokenParser.php index ee546e05f..72fbda77b 100644 --- a/lib/symfony/twig-bridge/TokenParser/TransDefaultDomainTokenParser.php +++ b/lib/symfony/twig-bridge/TokenParser/TransDefaultDomainTokenParser.php @@ -12,7 +12,6 @@ namespace Symfony\Bridge\Twig\TokenParser; use Symfony\Bridge\Twig\Node\TransDefaultDomainNode; -use Twig\Node\Node; use Twig\Token; use Twig\TokenParser\AbstractTokenParser; @@ -24,9 +23,7 @@ use Twig\TokenParser\AbstractTokenParser; class TransDefaultDomainTokenParser extends AbstractTokenParser { /** - * Parses a token and returns a node. - * - * @return Node + * {@inheritdoc} */ public function parse(Token $token) { @@ -38,9 +35,7 @@ class TransDefaultDomainTokenParser extends AbstractTokenParser } /** - * Gets the tag name associated with this token parser. - * - * @return string The tag name + * {@inheritdoc} */ public function getTag() { diff --git a/lib/symfony/twig-bridge/TokenParser/TransTokenParser.php b/lib/symfony/twig-bridge/TokenParser/TransTokenParser.php index ca2dae161..5f1e19acb 100644 --- a/lib/symfony/twig-bridge/TokenParser/TransTokenParser.php +++ b/lib/symfony/twig-bridge/TokenParser/TransTokenParser.php @@ -15,7 +15,6 @@ 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; @@ -28,11 +27,7 @@ use Twig\TokenParser\AbstractTokenParser; class TransTokenParser extends AbstractTokenParser { /** - * Parses a token and returns a node. - * - * @return Node - * - * @throws SyntaxError + * {@inheritdoc} */ public function parse(Token $token) { @@ -83,9 +78,7 @@ class TransTokenParser extends AbstractTokenParser } /** - * Gets the tag name associated with this token parser. - * - * @return string The tag name + * {@inheritdoc} */ public function getTag() { diff --git a/lib/symfony/twig-bridge/Translation/TwigExtractor.php b/lib/symfony/twig-bridge/Translation/TwigExtractor.php index a921582db..b7c787226 100644 --- a/lib/symfony/twig-bridge/Translation/TwigExtractor.php +++ b/lib/symfony/twig-bridge/Translation/TwigExtractor.php @@ -61,11 +61,7 @@ class TwigExtractor extends AbstractFileExtractor implements ExtractorInterface if ($file instanceof \SplFileInfo) { $path = $file->getRealPath() ?: $file->getPathname(); $name = $file instanceof SplFileInfo ? $file->getRelativePathname() : $path; - if (method_exists($e, 'setSourceContext')) { - $e->setSourceContext(new Source('', $name, $path)); - } else { - $e->setTemplateName($name); - } + $e->setSourceContext(new Source('', $name, $path)); } throw $e; @@ -106,9 +102,7 @@ class TwigExtractor extends AbstractFileExtractor implements ExtractorInterface } /** - * @param string|array $directory - * - * @return array + * {@inheritdoc} */ protected function extractFromDirectory($directory) { diff --git a/lib/symfony/twig-bridge/TwigEngine.php b/lib/symfony/twig-bridge/TwigEngine.php index 4789f3f4d..cfbb5d8f4 100644 --- a/lib/symfony/twig-bridge/TwigEngine.php +++ b/lib/symfony/twig-bridge/TwigEngine.php @@ -19,6 +19,7 @@ use Twig\Environment; use Twig\Error\Error; use Twig\Error\LoaderError; use Twig\Loader\ExistsLoaderInterface; +use Twig\Loader\SourceContextLoaderInterface; use Twig\Template; /** @@ -74,19 +75,24 @@ class TwigEngine implements EngineInterface, StreamingEngineInterface $loader = $this->environment->getLoader(); - if ($loader instanceof ExistsLoaderInterface || method_exists($loader, 'exists')) { - return $loader->exists((string) $name); - } + if (1 === Environment::MAJOR_VERSION && !$loader instanceof ExistsLoaderInterface) { + try { + // cast possible TemplateReferenceInterface to string because the + // EngineInterface supports them but LoaderInterface does not + if ($loader instanceof SourceContextLoaderInterface) { + $loader->getSourceContext((string) $name); + } else { + $loader->getSource((string) $name); + } + + return true; + } catch (LoaderError $e) { + } - try { - // cast possible TemplateReferenceInterface to string because the - // EngineInterface supports them but LoaderInterface does not - $loader->getSourceContext((string) $name)->getCode(); - } catch (LoaderError $e) { return false; } - return true; + return $loader->exists((string) $name); } /** diff --git a/lib/symfony/twig-bridge/UndefinedCallableHandler.php b/lib/symfony/twig-bridge/UndefinedCallableHandler.php index 9c2d18b4a..43cac82bc 100644 --- a/lib/symfony/twig-bridge/UndefinedCallableHandler.php +++ b/lib/symfony/twig-bridge/UndefinedCallableHandler.php @@ -71,6 +71,8 @@ class UndefinedCallableHandler } self::onUndefined($name, 'filter', self::$filterComponents[$name]); + + return true; } public static function onUndefinedFunction($name) @@ -80,6 +82,8 @@ class UndefinedCallableHandler } self::onUndefined($name, 'function', self::$functionComponents[$name]); + + return true; } private static function onUndefined($name, $type, $component) diff --git a/lib/symfony/twig-bridge/composer.json b/lib/symfony/twig-bridge/composer.json index 071b25b18..f4fb1c98a 100644 --- a/lib/symfony/twig-bridge/composer.json +++ b/lib/symfony/twig-bridge/composer.json @@ -17,13 +17,14 @@ ], "require": { "php": "^5.5.9|>=7.0.8", - "twig/twig": "^1.40|^2.9" + "twig/twig": "^1.41|^2.10" }, "require-dev": { + "fig/link-util": "^1.0", "symfony/asset": "~2.8|~3.0|~4.0", "symfony/dependency-injection": "~2.8|~3.0|~4.0", "symfony/finder": "~2.8|~3.0|~4.0", - "symfony/form": "^3.4.23|^4.2.4", + "symfony/form": "^3.4.31|^4.3.4", "symfony/http-foundation": "^3.3.11|~4.0", "symfony/http-kernel": "~3.2|~4.0", "symfony/polyfill-intl-icu": "~1.0", @@ -41,7 +42,7 @@ "symfony/workflow": "~3.3|~4.0" }, "conflict": { - "symfony/form": "<3.4.13|>=4.0,<4.0.13|>=4.1,<4.1.2", + "symfony/form": "<3.4.31|>=4.0,<4.3.4", "symfony/console": "<3.4" }, "suggest": { diff --git a/lib/symfony/twig-bundle/CacheWarmer/TemplateCacheWarmer.php b/lib/symfony/twig-bundle/CacheWarmer/TemplateCacheWarmer.php index 874bed33e..23abdbf99 100644 --- a/lib/symfony/twig-bundle/CacheWarmer/TemplateCacheWarmer.php +++ b/lib/symfony/twig-bundle/CacheWarmer/TemplateCacheWarmer.php @@ -32,7 +32,6 @@ class TemplateCacheWarmer implements CacheWarmerInterface, ServiceSubscriberInte * TemplateCacheWarmer constructor. * * @param ContainerInterface $container - * @param \Traversable $iterator */ public function __construct($container, \Traversable $iterator) { diff --git a/lib/symfony/twig-bundle/ContainerAwareRuntimeLoader.php b/lib/symfony/twig-bundle/ContainerAwareRuntimeLoader.php index 5ba6df599..7595f5674 100644 --- a/lib/symfony/twig-bundle/ContainerAwareRuntimeLoader.php +++ b/lib/symfony/twig-bundle/ContainerAwareRuntimeLoader.php @@ -49,5 +49,7 @@ class ContainerAwareRuntimeLoader implements RuntimeLoaderInterface if (null !== $this->logger) { $this->logger->warning(sprintf('Class "%s" is not configured as a Twig runtime. Add the "twig.runtime" tag to the related service in the container.', $class)); } + + return null; } } diff --git a/lib/symfony/twig-bundle/Controller/ExceptionController.php b/lib/symfony/twig-bundle/Controller/ExceptionController.php index ff47c3d2b..22753af96 100644 --- a/lib/symfony/twig-bundle/Controller/ExceptionController.php +++ b/lib/symfony/twig-bundle/Controller/ExceptionController.php @@ -18,6 +18,7 @@ use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; use Twig\Environment; use Twig\Error\LoaderError; use Twig\Loader\ExistsLoaderInterface; +use Twig\Loader\SourceContextLoaderInterface; /** * ExceptionController renders error or exception pages for a given @@ -32,8 +33,7 @@ class ExceptionController protected $debug; /** - * @param Environment $twig - * @param bool $debug Show error (false) or exception (true) pages by default + * @param bool $debug Show error (false) or exception (true) pages by default */ public function __construct(Environment $twig, $debug) { @@ -88,10 +88,9 @@ class ExceptionController } /** - * @param Request $request - * @param string $format - * @param int $code An HTTP response status code - * @param bool $showException + * @param string $format + * @param int $code An HTTP response status code + * @param bool $showException * * @return string */ @@ -122,23 +121,28 @@ class ExceptionController return sprintf('@Twig/Exception/%s.html.twig', $showException ? 'exception_full' : $name); } - // to be removed when the minimum required version of Twig is >= 3.0 + // to be removed when the minimum required version of Twig is >= 2.0 protected function templateExists($template) { $template = (string) $template; $loader = $this->twig->getLoader(); - if ($loader instanceof ExistsLoaderInterface || method_exists($loader, 'exists')) { - return $loader->exists($template); + + if (1 === Environment::MAJOR_VERSION && !$loader instanceof ExistsLoaderInterface) { + try { + if ($loader instanceof SourceContextLoaderInterface) { + $loader->getSourceContext($template); + } else { + $loader->getSource($template); + } + + return true; + } catch (LoaderError $e) { + } + + return false; } - try { - $loader->getSourceContext($template)->getCode(); - - return true; - } catch (LoaderError $e) { - } - - return false; + return $loader->exists($template); } } diff --git a/lib/symfony/twig-bundle/DependencyInjection/TwigExtension.php b/lib/symfony/twig-bundle/DependencyInjection/TwigExtension.php index 58e136a63..52ba0503e 100644 --- a/lib/symfony/twig-bundle/DependencyInjection/TwigExtension.php +++ b/lib/symfony/twig-bundle/DependencyInjection/TwigExtension.php @@ -150,18 +150,20 @@ class TwigExtension extends Extension } } - unset( - $config['form'], - $config['globals'], - $config['extensions'] - ); - if (isset($config['autoescape_service']) && isset($config['autoescape_service_method'])) { $config['autoescape'] = [new Reference($config['autoescape_service']), $config['autoescape_service_method']]; } - unset($config['autoescape_service'], $config['autoescape_service_method']); - $container->getDefinition('twig')->replaceArgument(1, $config); + $container->getDefinition('twig')->replaceArgument(1, array_intersect_key($config, [ + 'debug' => true, + 'charset' => true, + 'base_template_class' => true, + 'strict_variables' => true, + 'autoescape' => true, + 'cache' => true, + 'auto_reload' => true, + 'optimizations' => true, + ])); $container->registerForAutoconfiguration(\Twig_ExtensionInterface::class)->addTag('twig.extension'); $container->registerForAutoconfiguration(\Twig_LoaderInterface::class)->addTag('twig.loader'); @@ -255,9 +257,7 @@ class TwigExtension extends Extension } /** - * Returns the base path for the XSD files. - * - * @return string The XSD base path + * {@inheritdoc} */ public function getXsdValidationBasePath() { diff --git a/lib/symfony/twig-bundle/Tests/DependencyInjection/Compiler/TwigLoaderPassTest.php b/lib/symfony/twig-bundle/Tests/DependencyInjection/Compiler/TwigLoaderPassTest.php index 3b65273d6..a112b64b5 100644 --- a/lib/symfony/twig-bundle/Tests/DependencyInjection/Compiler/TwigLoaderPassTest.php +++ b/lib/symfony/twig-bundle/Tests/DependencyInjection/Compiler/TwigLoaderPassTest.php @@ -87,11 +87,9 @@ class TwigLoaderPassTest extends TestCase $this->assertEquals('test_loader_1', (string) $calls[1][1][0]); } - /** - * @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException - */ public function testMapperPassWithZeroTaggedLoaders() { + $this->expectException('Symfony\Component\DependencyInjection\Exception\LogicException'); $this->pass->process($this->builder); } } diff --git a/lib/symfony/twig-bundle/Tests/Functional/NoTemplatingEntryTest.php b/lib/symfony/twig-bundle/Tests/Functional/NoTemplatingEntryTest.php index dddfff76e..3d509c44e 100644 --- a/lib/symfony/twig-bundle/Tests/Functional/NoTemplatingEntryTest.php +++ b/lib/symfony/twig-bundle/Tests/Functional/NoTemplatingEntryTest.php @@ -27,7 +27,7 @@ class NoTemplatingEntryTest extends TestCase $container = $kernel->getContainer(); $content = $container->get('twig')->render('index.html.twig'); - $this->assertContains('{ a: b }', $content); + $this->assertStringContainsString('{ a: b }', $content); } protected function setUp() diff --git a/lib/symfony/twig-bundle/Tests/Loader/FilesystemLoaderTest.php b/lib/symfony/twig-bundle/Tests/Loader/FilesystemLoaderTest.php index 906a0bc10..7fa8dd2b4 100644 --- a/lib/symfony/twig-bundle/Tests/Loader/FilesystemLoaderTest.php +++ b/lib/symfony/twig-bundle/Tests/Loader/FilesystemLoaderTest.php @@ -51,11 +51,9 @@ class FilesystemLoaderTest extends TestCase $this->assertTrue($loader->exists($template)); } - /** - * @expectedException \Twig\Error\LoaderError - */ public function testTwigErrorIfLocatorThrowsInvalid() { + $this->expectException('Twig\Error\LoaderError'); $parser = $this->getMockBuilder('Symfony\Component\Templating\TemplateNameParserInterface')->getMock(); $parser ->expects($this->once()) @@ -75,11 +73,9 @@ class FilesystemLoaderTest extends TestCase $loader->getCacheKey('name.format.engine'); } - /** - * @expectedException \Twig\Error\LoaderError - */ public function testTwigErrorIfLocatorReturnsFalse() { + $this->expectException('Twig\Error\LoaderError'); $parser = $this->getMockBuilder('Symfony\Component\Templating\TemplateNameParserInterface')->getMock(); $parser ->expects($this->once()) @@ -99,12 +95,10 @@ class FilesystemLoaderTest extends TestCase $loader->getCacheKey('name.format.engine'); } - /** - * @expectedException \Twig\Error\LoaderError - * @expectedExceptionMessageRegExp /Unable to find template "name\.format\.engine" \(looked into: .*Tests.Loader.\.\..DependencyInjection.Fixtures.Resources.views\)/ - */ public function testTwigErrorIfTemplateDoesNotExist() { + $this->expectException('Twig\Error\LoaderError'); + $this->expectExceptionMessageRegExp('/Unable to find template "name\.format\.engine" \(looked into: .*Tests.Loader.\.\..DependencyInjection.Fixtures.Resources.views\)/'); $parser = $this->getMockBuilder('Symfony\Component\Templating\TemplateNameParserInterface')->getMock(); $locator = $this->getMockBuilder('Symfony\Component\Config\FileLocatorInterface')->getMock(); diff --git a/lib/symfony/twig-bundle/TwigEngine.php b/lib/symfony/twig-bundle/TwigEngine.php index 39115199e..f2dc6b556 100644 --- a/lib/symfony/twig-bundle/TwigEngine.php +++ b/lib/symfony/twig-bundle/TwigEngine.php @@ -13,7 +13,6 @@ namespace Symfony\Bundle\TwigBundle; use Symfony\Bridge\Twig\TwigEngine as BaseEngine; use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface; -use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; use Symfony\Component\Config\FileLocatorInterface; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Templating\TemplateNameParserInterface; @@ -36,28 +35,6 @@ class TwigEngine extends BaseEngine implements EngineInterface $this->locator = $locator; } - /** - * {@inheritdoc} - */ - public function render($name, array $parameters = []) - { - try { - return parent::render($name, $parameters); - } 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 - $name = $e->getTemplateName(); - $path = (string) $this->locator->locate($this->parser->parse($name)); - $e->setTemplateName($path); - } catch (\Exception $e2) { - } - } - - throw $e; - } - } - /** * {@inheritdoc} * diff --git a/lib/symfony/twig-bundle/composer.json b/lib/symfony/twig-bundle/composer.json index 4cc08e1b3..f48e3bc07 100644 --- a/lib/symfony/twig-bundle/composer.json +++ b/lib/symfony/twig-bundle/composer.json @@ -23,7 +23,7 @@ "symfony/http-foundation": "~2.8|~3.0|~4.0", "symfony/http-kernel": "^3.3|~4.0", "symfony/polyfill-ctype": "~1.8", - "twig/twig": "~1.40|~2.9" + "twig/twig": "~1.41|~2.10" }, "require-dev": { "symfony/asset": "~2.8|~3.0|~4.0", @@ -37,7 +37,7 @@ "symfony/yaml": "~2.8|~3.0|~4.0", "symfony/framework-bundle": "^3.3.11|~4.0", "symfony/web-link": "~3.3|~4.0", - "doctrine/annotations": "~1.0", + "doctrine/annotations": "~1.7", "doctrine/cache": "~1.0" }, "conflict": { diff --git a/lib/symfony/var-dumper/Caster/DateCaster.php b/lib/symfony/var-dumper/Caster/DateCaster.php index 40289a930..f3258b19a 100644 --- a/lib/symfony/var-dumper/Caster/DateCaster.php +++ b/lib/symfony/var-dumper/Caster/DateCaster.php @@ -85,12 +85,12 @@ class DateCaster public static function castPeriod(\DatePeriod $p, array $a, Stub $stub, $isNested, $filter) { - if (\defined('HHVM_VERSION_ID') || \PHP_VERSION_ID < 50620 || (\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70005)) { // see https://bugs.php.net/bug.php?id=71635 + if (\defined('HHVM_VERSION_ID') || \PHP_VERSION_ID < 50620 || (\PHP_VERSION_ID >= 70000 && \PHP_VERSION_ID < 70005)) { // see https://bugs.php.net/71635 return $a; } $dates = []; - if (\PHP_VERSION_ID >= 70107) { // see https://bugs.php.net/bug.php?id=74639 + if (\PHP_VERSION_ID >= 70107) { // see https://bugs.php.net/74639 foreach (clone $p as $i => $d) { if (3 === $i) { $now = new \DateTimeImmutable(); diff --git a/lib/symfony/var-dumper/Caster/SplCaster.php b/lib/symfony/var-dumper/Caster/SplCaster.php index a223adb7f..283c5613d 100644 --- a/lib/symfony/var-dumper/Caster/SplCaster.php +++ b/lib/symfony/var-dumper/Caster/SplCaster.php @@ -90,6 +90,12 @@ class SplCaster $prefix = Caster::PREFIX_VIRTUAL; + if (false === $c->getPathname()) { + $a[$prefix.'⚠'] = 'The parent constructor was not called: the object is in an invalid state'; + + return $a; + } + foreach ($map as $key => $accessor) { try { $a[$prefix.$key] = $c->$accessor(); diff --git a/lib/symfony/var-dumper/Cloner/AbstractCloner.php b/lib/symfony/var-dumper/Cloner/AbstractCloner.php index de09f1803..10d78b244 100644 --- a/lib/symfony/var-dumper/Cloner/AbstractCloner.php +++ b/lib/symfony/var-dumper/Cloner/AbstractCloner.php @@ -82,6 +82,8 @@ abstract class AbstractCloner implements ClonerInterface 'Symfony\Component\Debug\Exception\SilencedErrorContext' => ['Symfony\Component\VarDumper\Caster\ExceptionCaster', 'castSilencedErrorContext'], 'PHPUnit_Framework_MockObject_MockObject' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'PHPUnit\Framework\MockObject\MockObject' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], + 'PHPUnit\Framework\MockObject\Stub' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], 'Prophecy\Prophecy\ProphecySubjectInterface' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], 'Mockery\MockInterface' => ['Symfony\Component\VarDumper\Caster\StubCaster', 'cutInternals'], diff --git a/lib/symfony/var-dumper/Cloner/Data.php b/lib/symfony/var-dumper/Cloner/Data.php index bb5ee94d8..d14c5aa00 100644 --- a/lib/symfony/var-dumper/Cloner/Data.php +++ b/lib/symfony/var-dumper/Cloner/Data.php @@ -34,7 +34,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate } /** - * @return string The type of the value + * @return string|null The type of the value */ public function getType() { @@ -58,10 +58,12 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate if (Stub::TYPE_RESOURCE === $item->type) { return $item->class.' resource'; } + + return null; } /** - * @param bool $recursive Whether values should be resolved recursively or not + * @param array|bool $recursive Whether values should be resolved recursively or not * * @return string|int|float|bool|array|Data[]|null A native representation of the original value */ @@ -127,6 +129,8 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate return $item instanceof Stub || [] === $item ? $data : $item; } + + return null; } public function __isset($key) @@ -182,7 +186,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate * * @param int $maxDepth The max dumped depth level * - * @return self A clone of $this + * @return static */ public function withMaxDepth($maxDepth) { @@ -197,7 +201,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate * * @param int $maxItemsPerDepth The max number of items dumped per depth level * - * @return self A clone of $this + * @return static */ public function withMaxItemsPerDepth($maxItemsPerDepth) { @@ -212,7 +216,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate * * @param bool $useRefHandles False to hide global ref. handles * - * @return self A clone of $this + * @return static */ public function withRefHandles($useRefHandles) { @@ -227,7 +231,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate * * @param string|int $key The key to seek to * - * @return self|null A clone of $this or null if the key is not set + * @return static|null Null if the key is not set */ public function seek($key) { @@ -237,7 +241,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate $item = $item->value; } if (!($item = $this->getStub($item)) instanceof Stub || !$item->position) { - return; + return null; } $keys = [$key]; @@ -252,7 +256,7 @@ class Data implements \ArrayAccess, \Countable, \IteratorAggregate case Stub::TYPE_RESOURCE: break; default: - return; + return null; } $data = null; diff --git a/lib/symfony/var-dumper/Cloner/DumperInterface.php b/lib/symfony/var-dumper/Cloner/DumperInterface.php index cb498ff70..912bb5213 100644 --- a/lib/symfony/var-dumper/Cloner/DumperInterface.php +++ b/lib/symfony/var-dumper/Cloner/DumperInterface.php @@ -40,21 +40,21 @@ interface DumperInterface /** * Dumps while entering an hash. * - * @param Cursor $cursor The Cursor position in the dump - * @param int $type A Cursor::HASH_* const for the type of hash - * @param string $class The object class, resource type or array count - * @param bool $hasChild When the dump of the hash has child item + * @param Cursor $cursor The Cursor position in the dump + * @param int $type A Cursor::HASH_* const for the type of hash + * @param string|int $class The object class, resource type or array count + * @param bool $hasChild When the dump of the hash has child item */ public function enterHash(Cursor $cursor, $type, $class, $hasChild); /** * Dumps while leaving an hash. * - * @param Cursor $cursor The Cursor position in the dump - * @param int $type A Cursor::HASH_* const for the type of hash - * @param string $class The object class, resource type or array count - * @param bool $hasChild When the dump of the hash has child item - * @param int $cut The number of items the hash has been cut by + * @param Cursor $cursor The Cursor position in the dump + * @param int $type A Cursor::HASH_* const for the type of hash + * @param string|int $class The object class, resource type or array count + * @param bool $hasChild When the dump of the hash has child item + * @param int $cut The number of items the hash has been cut by */ public function leaveHash(Cursor $cursor, $type, $class, $hasChild, $cut); } diff --git a/lib/symfony/var-dumper/Dumper/AbstractDumper.php b/lib/symfony/var-dumper/Dumper/AbstractDumper.php index 30cd1a1b1..87195bb6a 100644 --- a/lib/symfony/var-dumper/Dumper/AbstractDumper.php +++ b/lib/symfony/var-dumper/Dumper/AbstractDumper.php @@ -35,7 +35,7 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface protected $indentPad = ' '; protected $flags; - private $charset; + private $charset = ''; /** * @param callable|resource|string|null $output A line dumper callable, an opened stream or an output path, defaults to static::$defaultOutput @@ -154,6 +154,8 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface setlocale(LC_NUMERIC, $locale); } } + + return null; } /** @@ -185,13 +187,13 @@ abstract class AbstractDumper implements DataDumperInterface, DumperInterface /** * Converts a non-UTF-8 string to UTF-8. * - * @param string $s The non-UTF-8 string to convert + * @param string|null $s The non-UTF-8 string to convert * - * @return string The string converted to UTF-8 + * @return string|null The string converted to UTF-8 */ protected function utf8Encode($s) { - if (preg_match('//u', $s)) { + if (null === $s || preg_match('//u', $s)) { return $s; } diff --git a/lib/symfony/var-dumper/Dumper/CliDumper.php b/lib/symfony/var-dumper/Dumper/CliDumper.php index 2bd347d96..946df7825 100644 --- a/lib/symfony/var-dumper/Dumper/CliDumper.php +++ b/lib/symfony/var-dumper/Dumper/CliDumper.php @@ -28,7 +28,7 @@ class CliDumper extends AbstractDumper protected $maxStringWidth = 0; protected $styles = [ // See http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - 'default' => '38;5;208', + 'default' => '0;38;5;208', 'num' => '1;38;5;38', 'const' => '1;38;5;208', 'str' => '1;38;5;113', diff --git a/lib/symfony/var-dumper/Test/VarDumperTestTrait.php b/lib/symfony/var-dumper/Test/VarDumperTestTrait.php index aae113b6c..84c36f49c 100644 --- a/lib/symfony/var-dumper/Test/VarDumperTestTrait.php +++ b/lib/symfony/var-dumper/Test/VarDumperTestTrait.php @@ -41,6 +41,9 @@ trait VarDumperTestTrait $this->assertStringMatchesFormat(rtrim($dump), $this->getDump($data, null, $filter), $message); } + /** + * @return string|null + */ protected function getDump($data, $key = null, $filter = 0) { $flags = getenv('DUMP_LIGHT_ARRAY') ? CliDumper::DUMP_LIGHT_ARRAY : 0; @@ -52,7 +55,7 @@ trait VarDumperTestTrait $dumper->setColors(false); $data = $cloner->cloneVar($data, $filter)->withRefHandles(false); if (null !== $key && null === $data = $data->seek($key)) { - return; + return null; } return rtrim($dumper->dump($data, true)); diff --git a/lib/symfony/var-dumper/Tests/Caster/ExceptionCasterTest.php b/lib/symfony/var-dumper/Tests/Caster/ExceptionCasterTest.php index ea83e7716..738180f5b 100644 --- a/lib/symfony/var-dumper/Tests/Caster/ExceptionCasterTest.php +++ b/lib/symfony/var-dumper/Tests/Caster/ExceptionCasterTest.php @@ -52,7 +52,6 @@ Exception { › } } %s%eTests%eCaster%eExceptionCasterTest.php:40 { …} - Symfony\Component\VarDumper\Tests\Caster\ExceptionCasterTest->testDefaultSettings() {} %A EODUMP; @@ -71,8 +70,7 @@ EODUMP; › return new \Exception(''.$msg); › } } - %s%eTests%eCaster%eExceptionCasterTest.php:65 { …} - Symfony\Component\VarDumper\Tests\Caster\ExceptionCasterTest->testSeek() {} + %s%eTests%eCaster%eExceptionCasterTest.php:64 { …} %A EODUMP; @@ -96,8 +94,7 @@ Exception { › return new \Exception(''.$msg); › } } - %s%eTests%eCaster%eExceptionCasterTest.php:84 { …} - Symfony\Component\VarDumper\Tests\Caster\ExceptionCasterTest->testNoArgs() {} + %s%eTests%eCaster%eExceptionCasterTest.php:82 { …} %A EODUMP; diff --git a/lib/symfony/var-dumper/Tests/Caster/SplCasterTest.php b/lib/symfony/var-dumper/Tests/Caster/SplCasterTest.php index 984b340c6..67033df09 100644 --- a/lib/symfony/var-dumper/Tests/Caster/SplCasterTest.php +++ b/lib/symfony/var-dumper/Tests/Caster/SplCasterTest.php @@ -50,12 +50,12 @@ SplFileInfo { %A} EOTXT ], - ['https://google.com/about', <<<'EOTXT' + ['https://example.com/about', <<<'EOTXT' SplFileInfo { -%Apath: "https://google.com" +%Apath: "https://example.com" filename: "about" basename: "about" - pathname: "https://google.com/about" + pathname: "https://example.com/about" extension: "" realPath: false %A} @@ -202,6 +202,18 @@ Symfony\Component\VarDumper\Tests\Caster\MyArrayIterator { 0 => 234 ] } +EOTXT; + $this->assertDumpEquals($expected, $var); + } + + public function testBadSplFileInfo() + { + $var = new BadSplFileInfo(); + + $expected = <<assertDumpEquals($expected, $var); } @@ -211,3 +223,10 @@ class MyArrayIterator extends \ArrayIterator { private $foo = 123; } + +class BadSplFileInfo extends \SplFileInfo +{ + public function __construct() + { + } +} diff --git a/lib/symfony/var-dumper/Tests/Cloner/DataTest.php b/lib/symfony/var-dumper/Tests/Cloner/DataTest.php index 7d20bced3..d4b6c24c1 100644 --- a/lib/symfony/var-dumper/Tests/Cloner/DataTest.php +++ b/lib/symfony/var-dumper/Tests/Cloner/DataTest.php @@ -69,7 +69,7 @@ class DataTest extends TestCase $children = $data->getValue(); - $this->assertInternalType('array', $children); + $this->assertIsArray($children); $this->assertInstanceOf(Data::class, $children[0]); $this->assertInstanceOf(Data::class, $children[1]); diff --git a/lib/symfony/var-dumper/Tests/Dumper/FunctionsTest.php b/lib/symfony/var-dumper/Tests/Dumper/FunctionsTest.php index 0bd596c2a..7444d4bf5 100644 --- a/lib/symfony/var-dumper/Tests/Dumper/FunctionsTest.php +++ b/lib/symfony/var-dumper/Tests/Dumper/FunctionsTest.php @@ -26,7 +26,7 @@ class FunctionsTest extends TestCase ob_start(); $return = dump($var1); - $out = ob_get_clean(); + ob_end_clean(); $this->assertEquals($var1, $return); } @@ -41,7 +41,7 @@ class FunctionsTest extends TestCase ob_start(); $return = dump($var1, $var2, $var3); - $out = ob_get_clean(); + ob_end_clean(); $this->assertEquals([$var1, $var2, $var3], $return); } diff --git a/lib/symfony/web-profiler-bundle/Controller/ExceptionController.php b/lib/symfony/web-profiler-bundle/Controller/ExceptionController.php index d5b0f5e66..e82144b87 100644 --- a/lib/symfony/web-profiler-bundle/Controller/ExceptionController.php +++ b/lib/symfony/web-profiler-bundle/Controller/ExceptionController.php @@ -19,6 +19,7 @@ use Symfony\Component\HttpKernel\Profiler\Profiler; use Twig\Environment; use Twig\Error\LoaderError; use Twig\Loader\ExistsLoaderInterface; +use Twig\Loader\SourceContextLoaderInterface; /** * ExceptionController. @@ -118,17 +119,22 @@ class ExceptionController protected function templateExists($template) { $loader = $this->twig->getLoader(); - if ($loader instanceof ExistsLoaderInterface) { - return $loader->exists($template); + + if (1 === Environment::MAJOR_VERSION && !$loader instanceof ExistsLoaderInterface) { + try { + if ($loader instanceof SourceContextLoaderInterface) { + $loader->getSourceContext($template); + } else { + $loader->getSource($template); + } + + return true; + } catch (LoaderError $e) { + } + + return false; } - try { - $loader->getSource($template); - - return true; - } catch (LoaderError $e) { - } - - return false; + return $loader->exists($template); } } diff --git a/lib/symfony/web-profiler-bundle/Controller/RouterController.php b/lib/symfony/web-profiler-bundle/Controller/RouterController.php index bd4c945b1..7f2a2406a 100644 --- a/lib/symfony/web-profiler-bundle/Controller/RouterController.php +++ b/lib/symfony/web-profiler-bundle/Controller/RouterController.php @@ -78,8 +78,7 @@ class RouterController /** * Returns the routing traces associated to the given request. * - * @param RequestDataCollector $request - * @param string $method + * @param string $method * * @return array */ diff --git a/lib/symfony/web-profiler-bundle/DependencyInjection/WebProfilerExtension.php b/lib/symfony/web-profiler-bundle/DependencyInjection/WebProfilerExtension.php index 2b2f00bd3..19b75c59e 100644 --- a/lib/symfony/web-profiler-bundle/DependencyInjection/WebProfilerExtension.php +++ b/lib/symfony/web-profiler-bundle/DependencyInjection/WebProfilerExtension.php @@ -64,9 +64,7 @@ class WebProfilerExtension extends Extension } /** - * Returns the base path for the XSD files. - * - * @return string The XSD base path + * {@inheritdoc} */ public function getXsdValidationBasePath() { diff --git a/lib/symfony/web-profiler-bundle/Profiler/TemplateManager.php b/lib/symfony/web-profiler-bundle/Profiler/TemplateManager.php index 630de0c8b..4f8da03cb 100644 --- a/lib/symfony/web-profiler-bundle/Profiler/TemplateManager.php +++ b/lib/symfony/web-profiler-bundle/Profiler/TemplateManager.php @@ -42,8 +42,7 @@ class TemplateManager /** * Gets the template name for a given panel. * - * @param Profile $profile - * @param string $panel + * @param string $panel * * @return mixed * @@ -118,21 +117,22 @@ class TemplateManager protected function templateExists($template) { $loader = $this->twig->getLoader(); - if ($loader instanceof ExistsLoaderInterface) { - return $loader->exists($template); - } - try { - if ($loader instanceof SourceContextLoaderInterface || method_exists($loader, 'getSourceContext')) { - $loader->getSourceContext($template); - } else { - $loader->getSource($template); + if (1 === Environment::MAJOR_VERSION && !$loader instanceof ExistsLoaderInterface) { + try { + if ($loader instanceof SourceContextLoaderInterface) { + $loader->getSourceContext($template); + } else { + $loader->getSource($template); + } + + return true; + } catch (LoaderError $e) { } - return true; - } catch (LoaderError $e) { + return false; } - return false; + return $loader->exists($template); } } diff --git a/lib/symfony/web-profiler-bundle/Resources/views/Collector/translation.html.twig b/lib/symfony/web-profiler-bundle/Resources/views/Collector/translation.html.twig index cd85ce3ba..79c6e60ff 100644 --- a/lib/symfony/web-profiler-bundle/Resources/views/Collector/translation.html.twig +++ b/lib/symfony/web-profiler-bundle/Resources/views/Collector/translation.html.twig @@ -13,7 +13,7 @@ {% set text %}
- Locale + Default locale {{ collector.locale|default('-') }} @@ -73,7 +73,7 @@
{{ collector.locale|default('-') }} - Locale + Default locale
{{ collector.fallbackLocales|join(', ')|default('-') }} @@ -152,7 +152,7 @@
{% else %} {% block fallback_messages %} - {{ helper.render_table(messages_fallback) }} + {{ helper.render_table(messages_fallback, true) }} {% endblock %} {% endif %}
@@ -185,11 +185,14 @@ {% endblock %} -{% macro render_table(messages) %} +{% macro render_table(messages, is_fallback) %} + {% if is_fallback %} + + {% endif %} @@ -200,6 +203,9 @@ {% for message in messages %} + {% if is_fallback %} + + {% endif %}
LocaleFallback localeDomain Times used Message ID
{{ message.locale }}{{ message.fallbackLocale|default('-') }}{{ message.domain }} {{ message.count }} diff --git a/lib/symfony/web-profiler-bundle/Resources/views/Profiler/toolbar_js.html.twig b/lib/symfony/web-profiler-bundle/Resources/views/Profiler/toolbar_js.html.twig index f13edfcfe..9da75d055 100644 --- a/lib/symfony/web-profiler-bundle/Resources/views/Profiler/toolbar_js.html.twig +++ b/lib/symfony/web-profiler-bundle/Resources/views/Profiler/toolbar_js.html.twig @@ -15,7 +15,7 @@ Sfjs.load( 'sfwdt{{ token }}', - '{{ path("_wdt", { "token": token }) }}', + '{{ path("_wdt", { "token": token })|escape('js') }}', function(xhr, el) { /* Evaluate embedded scripts inside the toolbar */ diff --git a/lib/symfony/web-profiler-bundle/Tests/Controller/ProfilerControllerTest.php b/lib/symfony/web-profiler-bundle/Tests/Controller/ProfilerControllerTest.php index a1e23041f..c55c67e53 100644 --- a/lib/symfony/web-profiler-bundle/Tests/Controller/ProfilerControllerTest.php +++ b/lib/symfony/web-profiler-bundle/Tests/Controller/ProfilerControllerTest.php @@ -98,9 +98,7 @@ class ProfilerControllerTest extends TestCase ->expects($this->exactly(2)) ->method('loadProfile') ->willReturnCallback(function ($token) { - if ('found' == $token) { - return new Profile($token); - } + return 'found' == $token ? new Profile($token) : null; }) ; diff --git a/lib/symfony/web-profiler-bundle/Tests/Profiler/TemplateManagerTest.php b/lib/symfony/web-profiler-bundle/Tests/Profiler/TemplateManagerTest.php index c6bc1cdba..ab4a42fc0 100644 --- a/lib/symfony/web-profiler-bundle/Tests/Profiler/TemplateManagerTest.php +++ b/lib/symfony/web-profiler-bundle/Tests/Profiler/TemplateManagerTest.php @@ -15,6 +15,8 @@ use Symfony\Bundle\WebProfilerBundle\Profiler\TemplateManager; use Symfony\Bundle\WebProfilerBundle\Tests\TestCase; use Symfony\Component\HttpKernel\Profiler\Profile; use Twig\Environment; +use Twig\Loader\LoaderInterface; +use Twig\Loader\SourceContextLoaderInterface; /** * Test for TemplateManager class. @@ -53,11 +55,9 @@ class TemplateManagerTest extends TestCase $this->templateManager = new TemplateManager($profiler, $twigEnvironment, $templates); } - /** - * @expectedException \Symfony\Component\HttpKernel\Exception\NotFoundHttpException - */ public function testGetNameOfInvalidTemplate() { + $this->expectException('Symfony\Component\HttpKernel\Exception\NotFoundHttpException'); $this->templateManager->getName(new Profile('token'), 'notexistingpanel'); } @@ -126,11 +126,16 @@ class TemplateManagerTest extends TestCase ->method('loadTemplate') ->willReturn('loadedTemplate'); - if (interface_exists('Twig\Loader\SourceContextLoaderInterface')) { - $loader = $this->getMockBuilder('Twig\Loader\SourceContextLoaderInterface')->getMock(); + if (Environment::MAJOR_VERSION > 1) { + $loader = $this->createMock(LoaderInterface::class); + $loader + ->expects($this->any()) + ->method('exists') + ->willReturn(true); } else { - $loader = $this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(); + $loader = $this->createMock(SourceContextLoaderInterface::class); } + $this->twigEnvironment->expects($this->any())->method('getLoader')->willReturn($loader); return $this->twigEnvironment; diff --git a/lib/symfony/yaml/Command/LintCommand.php b/lib/symfony/yaml/Command/LintCommand.php index cc19a5658..f6732ecf8 100644 --- a/lib/symfony/yaml/Command/LintCommand.php +++ b/lib/symfony/yaml/Command/LintCommand.php @@ -196,10 +196,13 @@ EOF } } + /** + * @return string|null + */ private function getStdin() { if (0 !== ftell(STDIN)) { - return; + return null; } $inputs = ''; diff --git a/lib/symfony/yaml/Dumper.php b/lib/symfony/yaml/Dumper.php index 0012df4a3..a496dcc88 100644 --- a/lib/symfony/yaml/Dumper.php +++ b/lib/symfony/yaml/Dumper.php @@ -115,7 +115,7 @@ class Dumper if ($value instanceof TaggedValue) { $output .= sprintf('%s%s !%s', $prefix, $dumpAsMap ? Inline::dump($key, $flags).':' : '-', $value->getTag()); - if ($inline - 1 <= 0) { + if ($inline - 1 <= 0 || null === $value->getValue() || is_scalar($value->getValue())) { $output .= ' '.$this->dump($value->getValue(), $inline - 1, 0, $flags)."\n"; } else { $output .= "\n"; diff --git a/lib/symfony/yaml/Inline.php b/lib/symfony/yaml/Inline.php index 5d71a1f30..7d3218a35 100644 --- a/lib/symfony/yaml/Inline.php +++ b/lib/symfony/yaml/Inline.php @@ -126,15 +126,15 @@ class Inline $result = self::parseScalar($value, $flags, null, $i, null === $tag, $references); } - if (null !== $tag) { - return new TaggedValue($tag, $result); - } - // some comments are allowed at the end if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) { throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)), self::$parsedLineNumber + 1, $value, self::$parsedFilename); } + if (null !== $tag) { + return new TaggedValue($tag, $result); + } + return $result; } finally { if (isset($mbEncoding)) { @@ -644,7 +644,7 @@ class Inline case 'null' === $scalarLower: case '' === $scalar: case '~' === $scalar: - return; + return null; case 'true' === $scalarLower: return true; case 'false' === $scalarLower: @@ -672,7 +672,7 @@ class Inline throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } - return; + return null; case 0 === strpos($scalar, '!!php/object:'): if (self::$objectSupport) { @trigger_error(self::getDeprecationMessage('The !!php/object: tag to indicate dumped PHP objects is deprecated since Symfony 3.1 and will be removed in 4.0. Use the !php/object (without the colon) tag instead.'), E_USER_DEPRECATED); @@ -684,7 +684,7 @@ class Inline throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } - return; + return null; case 0 === strpos($scalar, '!php/object'): if (self::$objectSupport) { return unserialize(self::parseScalar(substr($scalar, 12))); @@ -694,7 +694,7 @@ class Inline throw new ParseException('Object support when parsing a YAML file has been disabled.', self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } - return; + return null; case 0 === strpos($scalar, '!php/const:'): if (self::$constantSupport) { @trigger_error(self::getDeprecationMessage('The !php/const: tag to indicate dumped PHP constants is deprecated since Symfony 3.4 and will be removed in 4.0. Use the !php/const (without the colon) tag instead.'), E_USER_DEPRECATED); @@ -709,7 +709,7 @@ class Inline throw new ParseException(sprintf('The string "%s" could not be parsed as a constant. Have you forgotten to pass the "Yaml::PARSE_CONSTANT" flag to the parser?', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } - return; + return null; case 0 === strpos($scalar, '!php/const'): if (self::$constantSupport) { $i = 0; @@ -723,7 +723,7 @@ class Inline throw new ParseException(sprintf('The string "%s" could not be parsed as a constant. Have you forgotten to pass the "Yaml::PARSE_CONSTANT" flag to the parser?', $scalar), self::$parsedLineNumber + 1, $scalar, self::$parsedFilename); } - return; + return null; case 0 === strpos($scalar, '!!float '): return (float) substr($scalar, 8); case 0 === strpos($scalar, '!!binary '): @@ -795,7 +795,7 @@ class Inline private static function parseTag($value, &$i, $flags) { if ('!' !== $value[$i]) { - return; + return null; } $tagLength = strcspn($value, " \t\n", $i + 1); @@ -807,7 +807,7 @@ class Inline // Is followed by a scalar if ((!isset($value[$nextOffset]) || !\in_array($value[$nextOffset], ['[', '{'], true)) && 'tagged' !== $tag) { // Manage non-whitelisted scalars in {@link self::evaluateScalar()} - return; + return null; } // Built-in tags diff --git a/lib/symfony/yaml/Parser.php b/lib/symfony/yaml/Parser.php index cc094085c..7d6112e3b 100644 --- a/lib/symfony/yaml/Parser.php +++ b/lib/symfony/yaml/Parser.php @@ -436,6 +436,9 @@ class Parser $value = ''; foreach ($this->lines as $line) { + if ('' !== ltrim($line) && '#' === ltrim($line)[0]) { + continue; + } // If the indentation is not consistent at offset 0, it is to be considered as a ParseError if (0 === $this->offset && !$deprecatedUsage && isset($line[0]) && ' ' === $line[0]) { throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine, $this->filename); @@ -561,7 +564,7 @@ class Parser $oldLineIndentation = $this->getCurrentLineIndentation(); if (!$this->moveToNextLine()) { - return; + return ''; } if (null === $indentation) { @@ -604,7 +607,7 @@ class Parser } else { $this->moveToPreviousLine(); - return; + return ''; } if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) { @@ -612,7 +615,7 @@ class Parser // and therefore no nested list or mapping $this->moveToPreviousLine(); - return; + return ''; } $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem(); @@ -712,7 +715,7 @@ class Parser if (self::preg_match('/^(?:'.self::TAG_PATTERN.' +)?'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) { $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : ''; - $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers)); + $data = $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs((int) $modifiers)); if ('' !== $matches['tag']) { if ('!!binary' === $matches['tag']) { @@ -1099,14 +1102,17 @@ class Parser return $value; } + /** + * @return string|null + */ private function getLineTag($value, $flags, $nextLineCheck = true) { if ('' === $value || '!' !== $value[0] || 1 !== self::preg_match('/^'.self::TAG_PATTERN.' *( +#.*)?$/', $value, $matches)) { - return; + return null; } if ($nextLineCheck && !$this->isNextLineIndented()) { - return; + return null; } $tag = substr($matches['tag'], 1); diff --git a/lib/symfony/yaml/Tests/Command/LintCommandTest.php b/lib/symfony/yaml/Tests/Command/LintCommandTest.php index 2bf0286b6..349897859 100644 --- a/lib/symfony/yaml/Tests/Command/LintCommandTest.php +++ b/lib/symfony/yaml/Tests/Command/LintCommandTest.php @@ -48,7 +48,7 @@ bar'; $ret = $tester->execute(['filename' => $filename], ['decorated' => false]); $this->assertEquals(1, $ret, 'Returns 1 in case of error'); - $this->assertContains('Unable to parse at line 3 (near "bar").', trim($tester->getDisplay())); + $this->assertStringContainsString('Unable to parse at line 3 (near "bar").', trim($tester->getDisplay())); } public function testConstantAsKey() @@ -78,16 +78,14 @@ YAML; $this->assertSame(1, $ret, 'lint:yaml exits with code 1 in case of error'); } - /** - * @expectedException \RuntimeException - */ public function testLintFileNotReadable() { + $this->expectException('RuntimeException'); $tester = $this->createCommandTester(); $filename = $this->createFile(''); unlink($filename); - $ret = $tester->execute(['filename' => $filename], ['decorated' => false]); + $tester->execute(['filename' => $filename], ['decorated' => false]); } /** diff --git a/lib/symfony/yaml/Tests/DumperTest.php b/lib/symfony/yaml/Tests/DumperTest.php index 1a9cac6f7..1a1ef25a5 100644 --- a/lib/symfony/yaml/Tests/DumperTest.php +++ b/lib/symfony/yaml/Tests/DumperTest.php @@ -231,20 +231,18 @@ EOF; $this->assertEquals('{ foo: null, bar: 1 }', $dump, '->dump() does not dump objects when disabled'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\DumpException - */ public function testObjectSupportDisabledWithExceptions() { + $this->expectException('Symfony\Component\Yaml\Exception\DumpException'); $this->dumper->dump(['foo' => new A(), 'bar' => 1], 0, 0, Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE); } /** * @group legacy - * @expectedException \Symfony\Component\Yaml\Exception\DumpException */ public function testObjectSupportDisabledWithExceptionsPassingTrue() { + $this->expectException('Symfony\Component\Yaml\Exception\DumpException'); $this->dumper->dump(['foo' => new A(), 'bar' => 1], 0, 0, true); } @@ -527,6 +525,34 @@ YAML; $this->assertSame($expected, $yaml); } + public function testDumpingNotInlinedScalarTaggedValue() + { + $data = [ + 'user1' => new TaggedValue('user', 'jane'), + 'user2' => new TaggedValue('user', 'john'), + ]; + $expected = <<assertSame($expected, $this->dumper->dump($data, 2)); + } + + public function testDumpingNotInlinedNullTaggedValue() + { + $data = [ + 'foo' => new TaggedValue('bar', null), + ]; + $expected = <<assertSame($expected, $this->dumper->dump($data, 2)); + } + public function testDumpMultiLineStringAsScalarBlock() { $data = [ @@ -559,21 +585,17 @@ YAML; $this->assertSame("- \"a\\r\\nb\\nc\"\n", $this->dumper->dump(["a\r\nb\nc"], 2, 0, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK)); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The indentation must be greater than zero - */ public function testZeroIndentationThrowsException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The indentation must be greater than zero'); new Dumper(0); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The indentation must be greater than zero - */ public function testNegativeIndentationThrowsException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The indentation must be greater than zero'); new Dumper(-4); } } diff --git a/lib/symfony/yaml/Tests/InlineTest.php b/lib/symfony/yaml/Tests/InlineTest.php index 950c70230..014a12a70 100644 --- a/lib/symfony/yaml/Tests/InlineTest.php +++ b/lib/symfony/yaml/Tests/InlineTest.php @@ -62,21 +62,17 @@ class InlineTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage The constant "WRONG_CONSTANT" is not defined - */ public function testParsePhpConstantThrowsExceptionWhenUndefined() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('The constant "WRONG_CONSTANT" is not defined'); Inline::parse('!php/const WRONG_CONSTANT', Yaml::PARSE_CONSTANT); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessageRegExp #The string "!php/const PHP_INT_MAX" could not be parsed as a constant.*# - */ public function testParsePhpConstantThrowsExceptionOnInvalidType() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessageRegExp('#The string "!php/const PHP_INT_MAX" could not be parsed as a constant.*#'); Inline::parse('!php/const PHP_INT_MAX', Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE); } @@ -136,7 +132,7 @@ class InlineTest extends TestCase } $this->assertEquals('1.2', Inline::dump(1.2)); - $this->assertContains('fr', strtolower(setlocale(LC_NUMERIC, 0))); + $this->assertStringContainsStringIgnoringCase('fr', setlocale(LC_NUMERIC, 0)); } finally { setlocale(LC_NUMERIC, $locale); } @@ -149,46 +145,36 @@ class InlineTest extends TestCase $this->assertSame($value, Inline::parse(Inline::dump($value))); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Found unknown escape character "\V". - */ public function testParseScalarWithNonEscapedBlackslashShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Found unknown escape character "\V".'); Inline::parse('"Foo\Var"'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testParseScalarWithNonEscapedBlackslashAtTheEndShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); Inline::parse('"Foo\\"'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testParseScalarWithIncorrectlyQuotedStringShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $value = "'don't do somthin' like that'"; Inline::parse($value); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testParseScalarWithIncorrectlyDoubleQuotedStringShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $value = '"don"t do somthin" like that"'; Inline::parse($value); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testParseInvalidMappingKeyShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $value = '{ "foo " bar": "bar" }'; Inline::parse($value); } @@ -203,22 +189,24 @@ class InlineTest extends TestCase Inline::parse('{1:""}'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testParseInvalidMappingShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); Inline::parse('[foo] bar'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testParseInvalidSequenceShouldThrowException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); Inline::parse('{ foo: bar } bar'); } + public function testParseInvalidTaggedSequenceShouldThrowException() + { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + Inline::parse('!foo { bar: baz } qux', Yaml::PARSE_CUSTOM_TAGS); + } + public function testParseScalarWithCorrectlyQuotedStringShouldReturnString() { $value = "'don''t do somthin'' like that'"; @@ -281,21 +269,17 @@ class InlineTest extends TestCase $this->assertSame([$foo], Inline::parse('[*foo]', false, false, false, ['foo' => $foo])); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage A reference must contain at least one character at line 1. - */ public function testParseUnquotedAsterisk() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('A reference must contain at least one character at line 1.'); Inline::parse('{ foo: * }'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage A reference must contain at least one character at line 1. - */ public function testParseUnquotedAsteriskFollowedByAComment() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('A reference must contain at least one character at line 1.'); Inline::parse('{ foo: * #foo }'); } @@ -304,12 +288,8 @@ class InlineTest extends TestCase */ public function testParseUnquotedScalarStartingWithReservedIndicator($indicator) { - if (method_exists($this, 'expectExceptionMessage')) { - $this->expectException(ParseException::class); - $this->expectExceptionMessage(sprintf('cannot start a plain scalar; you need to quote the scalar at line 1 (near "%sfoo ").', $indicator)); - } else { - $this->setExpectedException(ParseException::class, sprintf('cannot start a plain scalar; you need to quote the scalar at line 1 (near "%sfoo ").', $indicator)); - } + $this->expectException(ParseException::class); + $this->expectExceptionMessage(sprintf('cannot start a plain scalar; you need to quote the scalar at line 1 (near "%sfoo ").', $indicator)); Inline::parse(sprintf('{ foo: %sfoo }', $indicator)); } @@ -324,12 +304,8 @@ class InlineTest extends TestCase */ public function testParseUnquotedScalarStartingWithScalarIndicator($indicator) { - if (method_exists($this, 'expectExceptionMessage')) { - $this->expectException(ParseException::class); - $this->expectExceptionMessage(sprintf('cannot start a plain scalar; you need to quote the scalar at line 1 (near "%sfoo ").', $indicator)); - } else { - $this->setExpectedException(ParseException::class, sprintf('cannot start a plain scalar; you need to quote the scalar at line 1 (near "%sfoo ").', $indicator)); - } + $this->expectException(ParseException::class); + $this->expectExceptionMessage(sprintf('cannot start a plain scalar; you need to quote the scalar at line 1 (near "%sfoo ").', $indicator)); Inline::parse(sprintf('{ foo: %sfoo }', $indicator)); } @@ -693,15 +669,11 @@ class InlineTest extends TestCase /** * @dataProvider getInvalidBinaryData - * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ public function testParseInvalidBinaryData($data, $expectedMessage) { - if (method_exists($this, 'expectException')) { - $this->expectExceptionMessageRegExp($expectedMessage); - } else { - $this->setExpectedExceptionRegExp(ParseException::class, $expectedMessage); - } + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessageRegExp($expectedMessage); Inline::parse($data); } @@ -716,12 +688,10 @@ class InlineTest extends TestCase ]; } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Malformed inline YAML string: {this, is not, supported} at line 1. - */ public function testNotSupportedMissingValue() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Malformed inline YAML string: {this, is not, supported} at line 1.'); Inline::parse('{this, is not, supported}'); } @@ -805,12 +775,10 @@ class InlineTest extends TestCase $this->assertSame(['foo' => 'bar'], Inline::parse('{ foo: !str bar }')); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Unexpected end of line, expected one of ",}" at line 1 (near "{abc: 'def'"). - */ public function testUnfinishedInlineMap() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Unexpected end of line, expected one of ",}" at line 1 (near "{abc: \'def\'").'); Inline::parse("{abc: 'def'"); } } diff --git a/lib/symfony/yaml/Tests/ParserTest.php b/lib/symfony/yaml/Tests/ParserTest.php index 0f25732ab..dc7c122d5 100644 --- a/lib/symfony/yaml/Tests/ParserTest.php +++ b/lib/symfony/yaml/Tests/ParserTest.php @@ -12,7 +12,6 @@ namespace Symfony\Component\Yaml\Tests; use PHPUnit\Framework\TestCase; -use Symfony\Component\Yaml\Exception\ParseException; use Symfony\Component\Yaml\Parser; use Symfony\Component\Yaml\Tag\TaggedValue; use Symfony\Component\Yaml\Yaml; @@ -46,14 +45,12 @@ class ParserTest extends TestCase if (E_USER_DEPRECATED !== $type) { restore_error_handler(); - if (class_exists('PHPUnit_Util_ErrorHandler')) { - return \call_user_func_array('PHPUnit_Util_ErrorHandler::handleError', \func_get_args()); - } - return \call_user_func_array('PHPUnit\Util\ErrorHandler::handleError', \func_get_args()); } $deprecations[] = $msg; + + return null; }); } @@ -63,7 +60,7 @@ class ParserTest extends TestCase restore_error_handler(); $this->assertCount(1, $deprecations); - $this->assertContains(true !== $deprecated ? $deprecated : 'Using the comma as a group separator for floats is deprecated since Symfony 3.2 and will be removed in 4.0 on line 1.', $deprecations[0]); + $this->assertStringContainsString(true !== $deprecated ? $deprecated : 'Using the comma as a group separator for floats is deprecated since Symfony 3.2 and will be removed in 4.0 on line 1.', $deprecations[0]); } } @@ -113,7 +110,7 @@ class ParserTest extends TestCase foreach ($yamls as $yaml) { try { - $content = $this->parser->parse($yaml); + $this->parser->parse($yaml); $this->fail('YAML files must not contain tabs'); } catch (\Exception $e) { @@ -610,10 +607,10 @@ YAML; /** * @dataProvider invalidDumpedObjectProvider - * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ public function testObjectsSupportDisabledWithExceptions($yaml) { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $this->parser->parse($yaml, Yaml::PARSE_EXCEPTION_ON_INVALID_TYPE); } @@ -631,10 +628,10 @@ YAML; /** * @group legacy * @dataProvider invalidDumpedObjectProvider - * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ public function testObjectsSupportDisabledWithExceptionsUsingBooleanToggles($yaml) { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $this->parser->parse($yaml, true); } @@ -677,11 +674,9 @@ EOF; } } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testUnindentedCollectionException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $yaml = <<<'EOF' collection: @@ -694,11 +689,9 @@ EOF; $this->parser->parse($yaml); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testShortcutKeyUnindentedCollectionException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $yaml = <<<'EOF' collection: @@ -710,12 +703,10 @@ EOF; $this->parser->parse($yaml); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessageRegExp /^Multiple documents are not supported.+/ - */ public function testMultipleDocumentsNotSupportedException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessageRegExp('/^Multiple documents are not supported.+/'); Yaml::parse(<<<'EOL' # Ranking of 1998 home runs --- @@ -731,11 +722,9 @@ EOL ); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testSequenceInAMapping() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); Yaml::parse(<<<'EOF' yaml: hash: me @@ -840,10 +829,10 @@ EOT; /** * @dataProvider getParseExceptionNotAffectedMultiLineStringLastResortParsing - * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ public function testParseExceptionNotAffectedByMultiLineStringLastResortParsing($yaml) { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); $this->parser->parse($yaml); } @@ -873,11 +862,9 @@ EOT; $this->assertSame($expected, $this->parser->parse($yaml)); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - */ public function testMappingInASequence() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); Yaml::parse(<<<'EOF' yaml: - array stuff @@ -886,12 +873,10 @@ EOF ); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage missing colon - */ public function testScalarInSequence() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('missing colon'); Yaml::parse(<<<'EOF' foo: - bar @@ -1242,12 +1227,10 @@ EOF; $this->assertEquals($expected, $this->parser->parse($yaml)); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage A colon cannot be used in an unquoted mapping value - */ public function testColonInMappingValueException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('A colon cannot be used in an unquoted mapping value'); $yaml = <<<'EOF' foo: bar: baz EOF; @@ -1481,15 +1464,11 @@ EOT /** * @dataProvider getInvalidBinaryData - * @expectedException \Symfony\Component\Yaml\Exception\ParseException */ public function testParseInvalidBinaryData($data, $expectedMessage) { - if (method_exists($this, 'expectException')) { - $this->expectExceptionMessageRegExp($expectedMessage); - } else { - $this->setExpectedExceptionRegExp(ParseException::class, $expectedMessage); - } + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessageRegExp($expectedMessage); $this->parser->parse($data); } @@ -1556,12 +1535,8 @@ EOT; */ public function testParserThrowsExceptionWithCorrectLineNumber($lineNumber, $yaml) { - if (method_exists($this, 'expectException')) { - $this->expectException('\Symfony\Component\Yaml\Exception\ParseException'); - $this->expectExceptionMessage(sprintf('Unexpected characters near "," at line %d (near "bar: "123",").', $lineNumber)); - } else { - $this->setExpectedException('\Symfony\Component\Yaml\Exception\ParseException', sprintf('Unexpected characters near "," at line %d (near "bar: "123",").', $lineNumber)); - } + $this->expectException('\Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage(sprintf('Unexpected characters near "," at line %d (near "bar: "123",").', $lineNumber)); $this->parser->parse($yaml); } @@ -1803,12 +1778,10 @@ YAML ]; } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Tags support is not enabled. Enable the `Yaml::PARSE_CUSTOM_TAGS` flag to use "!iterator" at line 1 (near "!iterator [foo]"). - */ public function testCustomTagsDisabled() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Tags support is not enabled. Enable the `Yaml::PARSE_CUSTOM_TAGS` flag to use "!iterator" at line 1 (near "!iterator [foo]").'); $this->parser->parse('!iterator [foo]'); } @@ -1821,12 +1794,10 @@ YAML $this->assertEquals('!iterator foo', $this->parser->parse('!iterator foo')); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage The built-in tag "!!foo" is not implemented at line 1 (near "!!foo"). - */ public function testExceptionWhenUsingUnsuportedBuiltInTags() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('The built-in tag "!!foo" is not implemented at line 1 (near "!!foo").'); $this->parser->parse('!!foo'); } @@ -1876,12 +1847,10 @@ YAML; $this->parser->parse($yaml); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Unable to parse at line 1 (near "[parameters]"). - */ public function testParsingIniThrowsException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Unable to parse at line 1 (near "[parameters]").'); $ini = <<assertEquals($trickyVal, $arrayFromYaml); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Reference "foo" does not exist at line 2 - */ public function testParserCleansUpReferencesBetweenRuns() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Reference "foo" does not exist at line 2'); $yaml = <<assertInternalType('array', $this->parser->parseFile(__DIR__.'/Fixtures/index.yml')); + $this->assertIsArray($this->parser->parseFile(__DIR__.'/Fixtures/index.yml')); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessageRegExp #^File ".+/Fixtures/nonexistent.yml" does not exist\.$# - */ public function testParsingNonExistentFilesThrowsException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessageRegExp('#^File ".+/Fixtures/nonexistent.yml" does not exist\.$#'); $this->parser->parseFile(__DIR__.'/Fixtures/nonexistent.yml'); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessageRegExp #^File ".+/Fixtures/not_readable.yml" cannot be read\.$# - */ public function testParsingNotReadableFilesThrowsException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessageRegExp('#^File ".+/Fixtures/not_readable.yml" cannot be read\.$#'); if ('\\' === \DIRECTORY_SEPARATOR) { $this->markTestSkipped('chmod is not supported on Windows'); } @@ -2165,12 +2128,10 @@ YAML; $this->assertEquals($expected, $this->parser->parse($yaml, Yaml::PARSE_OBJECT_FOR_MAP)); } - /** - * @expectedException \Symfony\Component\Yaml\Exception\ParseException - * @expectedExceptionMessage Reference "foo" does not exist - */ public function testEvalRefException() { + $this->expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Reference "foo" does not exist'); $yaml = <<expectException('Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage('Circular reference [foo, bar, foo] detected'); $this->parser->parse($yaml, Yaml::PARSE_CUSTOM_TAGS); } @@ -2292,6 +2253,60 @@ YAML; return $tests; } + + public function testMultiLineComment() + { + $yaml = <<assertSame(['parameters' => 'abc'], $this->parser->parse($yaml)); + } + + public function testParseValueWithModifiers() + { + $yaml = <<assertSame( + [ + 'parameters' => [ + 'abc' => implode("\n", ['one', 'two', 'three', 'four', 'five']), + ], + ], + $this->parser->parse($yaml) + ); + } + + public function testParseValueWithNegativeModifiers() + { + $yaml = <<assertSame( + [ + 'parameters' => [ + 'abc' => implode("\n", ['one', 'two', 'three', 'four', 'five']), + ], + ], + $this->parser->parse($yaml) + ); + } } class B diff --git a/lib/symfony/yaml/Tests/YamlTest.php b/lib/symfony/yaml/Tests/YamlTest.php index 5a792c511..7be126649 100644 --- a/lib/symfony/yaml/Tests/YamlTest.php +++ b/lib/symfony/yaml/Tests/YamlTest.php @@ -24,21 +24,17 @@ class YamlTest extends TestCase $this->assertEquals($data, $parsed); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The indentation must be greater than zero - */ public function testZeroIndentationThrowsException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The indentation must be greater than zero'); Yaml::dump(['lorem' => 'ipsum', 'dolor' => 'sit'], 2, 0); } - /** - * @expectedException \InvalidArgumentException - * @expectedExceptionMessage The indentation must be greater than zero - */ public function testNegativeIndentationThrowsException() { + $this->expectException('InvalidArgumentException'); + $this->expectExceptionMessage('The indentation must be greater than zero'); Yaml::dump(['lorem' => 'ipsum', 'dolor' => 'sit'], 2, -4); } } diff --git a/lib/twig/twig/.gitignore b/lib/twig/twig/.gitignore index 31103621c..8a29959e2 100644 --- a/lib/twig/twig/.gitignore +++ b/lib/twig/twig/.gitignore @@ -3,3 +3,4 @@ /ext/twig/autom4te.cache/ /phpunit.xml /vendor +.phpunit.result.cache diff --git a/lib/twig/twig/.php_cs.dist b/lib/twig/twig/.php_cs.dist index 1b31c0a3d..b81882fbf 100644 --- a/lib/twig/twig/.php_cs.dist +++ b/lib/twig/twig/.php_cs.dist @@ -4,6 +4,8 @@ return PhpCsFixer\Config::create() ->setRules([ '@Symfony' => true, '@Symfony:risky' => true, + '@PHPUnit75Migration:risky' => true, + 'php_unit_dedicate_assert' => ['target' => '5.6'], 'array_syntax' => ['syntax' => 'short'], 'php_unit_fqcn_annotation' => true, 'no_unreachable_default_argument_value' => false, diff --git a/lib/twig/twig/.travis.yml b/lib/twig/twig/.travis.yml index 291b4a9b8..ff6132b35 100644 --- a/lib/twig/twig/.travis.yml +++ b/lib/twig/twig/.travis.yml @@ -1,5 +1,7 @@ language: php +dist: trusty + sudo: false cache: @@ -7,8 +9,11 @@ cache: - vendor - $HOME/.composer/cache/files + env: - - TWIG_EXT=no + global: + - TWIG_EXT=no + - SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT=1 before_install: - phpenv config-rm xdebug.ini || return 0 @@ -25,9 +30,6 @@ script: ./vendor/bin/simple-phpunit jobs: fast_finish: true include: - - php: 5.4 - - php: 5.4 - env: TWIG_EXT=yes - php: 5.5 - php: 5.5 env: TWIG_EXT=yes diff --git a/lib/twig/twig/CHANGELOG b/lib/twig/twig/CHANGELOG index 61b3ba408..b9833e51e 100644 --- a/lib/twig/twig/CHANGELOG +++ b/lib/twig/twig/CHANGELOG @@ -1,3 +1,16 @@ +* 1.42.4 (2019-11-11) + + * optimized "block('foo') ?? 'bar" + * added supported for exponential numbers + +* 1.42.3 (2019-08-24) + + * fixed the "split" filter when the delimiter is "0" + * fixed the "empty" test on Traversable instances + * fixed cache when opcache is installed but disabled + * fixed PHP 7.4 compatibility + * bumped the minimal PHP version to 5.5 + * 1.42.2 (2019-06-18) * Display partial output (PHP buffer) when an error occurs in debug mode diff --git a/lib/twig/twig/README.rst b/lib/twig/twig/README.rst index f33ea336d..d896ff500 100644 --- a/lib/twig/twig/README.rst +++ b/lib/twig/twig/README.rst @@ -7,6 +7,15 @@ and documentation). Twig uses a syntax similar to the Django and Jinja template languages which inspired the Twig runtime environment. +Sponsors +-------- + +.. raw:: html + + + Blackfire.io + + More Information ---------------- diff --git a/lib/twig/twig/composer.json b/lib/twig/twig/composer.json index 2f104658c..9807aa771 100644 --- a/lib/twig/twig/composer.json +++ b/lib/twig/twig/composer.json @@ -24,12 +24,12 @@ } ], "require": { - "php": ">=5.4.0", + "php": ">=5.5.0", "symfony/polyfill-ctype": "^1.8" }, "require-dev": { - "symfony/phpunit-bridge": "^3.4.19|^4.1.8|^5.0", - "symfony/debug": "^2.7", + "symfony/phpunit-bridge": "^4.4@dev|^5.0", + "symfony/debug": "^3.4|^4.2", "psr/container": "^1.0" }, "autoload": { @@ -40,6 +40,11 @@ "Twig\\" : "src/" } }, + "autoload-dev": { + "psr-4" : { + "Twig\\Tests\\" : "tests" + } + }, "extra": { "branch-alias": { "dev-master": "1.42-dev" diff --git a/lib/twig/twig/ext/twig/php_twig.h b/lib/twig/twig/ext/twig/php_twig.h index 0fdc539a9..6cc47b689 100644 --- a/lib/twig/twig/ext/twig/php_twig.h +++ b/lib/twig/twig/ext/twig/php_twig.h @@ -15,7 +15,7 @@ #ifndef PHP_TWIG_H #define PHP_TWIG_H -#define PHP_TWIG_VERSION "1.42.2" +#define PHP_TWIG_VERSION "1.42.4" #include "php.h" diff --git a/lib/twig/twig/phpunit.xml.dist b/lib/twig/twig/phpunit.xml.dist deleted file mode 100644 index c35257f5d..000000000 --- a/lib/twig/twig/phpunit.xml.dist +++ /dev/null @@ -1,33 +0,0 @@ - - - - - - ./test/Twig/ - - - - - - - - - - - - - - - ./src/ - - - diff --git a/lib/twig/twig/src/Cache/FilesystemCache.php b/lib/twig/twig/src/Cache/FilesystemCache.php index 7e228799a..b7c1e438e 100644 --- a/lib/twig/twig/src/Cache/FilesystemCache.php +++ b/lib/twig/twig/src/Cache/FilesystemCache.php @@ -67,8 +67,8 @@ class FilesystemCache implements CacheInterface if (self::FORCE_BYTECODE_INVALIDATION == ($this->options & self::FORCE_BYTECODE_INVALIDATION)) { // Compile cached file into bytecode cache - if (\function_exists('opcache_invalidate')) { - opcache_invalidate($key, true); + if (\function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN)) { + @opcache_invalidate($key, true); } elseif (\function_exists('apc_compile_file')) { apc_compile_file($key); } diff --git a/lib/twig/twig/src/Environment.php b/lib/twig/twig/src/Environment.php index 509db8027..1f80f3a87 100644 --- a/lib/twig/twig/src/Environment.php +++ b/lib/twig/twig/src/Environment.php @@ -41,11 +41,11 @@ use Twig\TokenParser\TokenParserInterface; */ class Environment { - const VERSION = '1.42.2'; - const VERSION_ID = 14202; + const VERSION = '1.42.4'; + const VERSION_ID = 14204; const MAJOR_VERSION = 1; const MINOR_VERSION = 42; - const RELEASE_VERSION = 2; + const RELEASE_VERSION = 4; const EXTRA_VERSION = ''; protected $charset; @@ -515,7 +515,7 @@ class Environment * * This method should not be used as a generic way to load templates. * - * @param string $template The template name + * @param string $template The template source * @param string $name An optional name of the template to be used in error messages * * @return TemplateWrapper A template instance representing the given template name diff --git a/lib/twig/twig/src/Extension/CoreExtension.php b/lib/twig/twig/src/Extension/CoreExtension.php index 80ced9815..5f3cc24a1 100644 --- a/lib/twig/twig/src/Extension/CoreExtension.php +++ b/lib/twig/twig/src/Extension/CoreExtension.php @@ -790,7 +790,7 @@ function twig_join_filter($value, $glue = '', $and = null) */ function twig_split_filter(Environment $env, $value, $delimiter, $limit = null) { - if (!empty($delimiter)) { + if (\strlen($delimiter) > 0) { return null === $limit ? explode($delimiter, $value) : explode($delimiter, $value, $limit); } @@ -1507,6 +1507,10 @@ function twig_test_empty($value) return 0 == \count($value); } + if ($value instanceof \Traversable) { + return !iterator_count($value); + } + if (\is_object($value) && method_exists($value, '__toString')) { return '' === (string) $value; } diff --git a/lib/twig/twig/src/Lexer.php b/lib/twig/twig/src/Lexer.php index 8cae3597f..697a6cfa1 100644 --- a/lib/twig/twig/src/Lexer.php +++ b/lib/twig/twig/src/Lexer.php @@ -47,7 +47,7 @@ class Lexer implements \Twig_LexerInterface const STATE_INTERPOLATION = 4; const REGEX_NAME = '/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/A'; - const REGEX_NUMBER = '/[0-9]+(?:\.[0-9]+)?/A'; + const REGEX_NUMBER = '/[0-9]+(?:\.[0-9]+)?([Ee][\+\-][0-9]+)?/A'; const REGEX_STRING = '/"([^#"\\\\]*(?:\\\\.[^#"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\'/As'; const REGEX_DQ_STRING_DELIM = '/"/A'; const REGEX_DQ_STRING_PART = '/[^#"\\\\]*(?:(?:\\\\.|#(?!\{))[^#"\\\\]*)*/As'; diff --git a/lib/twig/twig/src/Node/Expression/NullCoalesceExpression.php b/lib/twig/twig/src/Node/Expression/NullCoalesceExpression.php index 49326d467..917d31a3b 100644 --- a/lib/twig/twig/src/Node/Expression/NullCoalesceExpression.php +++ b/lib/twig/twig/src/Node/Expression/NullCoalesceExpression.php @@ -22,11 +22,15 @@ class NullCoalesceExpression extends ConditionalExpression { public function __construct(\Twig_NodeInterface $left, \Twig_NodeInterface $right, $lineno) { - $test = new AndBinary( - new DefinedTest(clone $left, 'defined', new Node(), $left->getTemplateLine()), - new NotUnary(new NullTest($left, 'null', new Node(), $left->getTemplateLine()), $left->getTemplateLine()), - $left->getTemplateLine() - ); + $test = new DefinedTest(clone $left, 'defined', new Node(), $left->getTemplateLine()); + // for "block()", we don't need the null test as the return value is always a string + if (!$left instanceof BlockReferenceExpression) { + $test = new AndBinary( + $test, + new NotUnary(new NullTest($left, 'null', new Node(), $left->getTemplateLine()), $left->getTemplateLine()), + $left->getTemplateLine() + ); + } parent::__construct($test, $left, $right, $lineno); } diff --git a/lib/twig/twig/src/Template.php b/lib/twig/twig/src/Template.php index 435f8c67e..3f7447c12 100644 --- a/lib/twig/twig/src/Template.php +++ b/lib/twig/twig/src/Template.php @@ -537,7 +537,7 @@ abstract class Template implements \Twig_TemplateInterface if (self::METHOD_CALL !== $type) { $arrayItem = \is_bool($item) || \is_float($item) ? (int) $item : $item; - if (((\is_array($object) || $object instanceof \ArrayObject) && (isset($object[$arrayItem]) || \array_key_exists($arrayItem, $object))) + if (((\is_array($object) || $object instanceof \ArrayObject) && (isset($object[$arrayItem]) || \array_key_exists($arrayItem, (array) $object))) || ($object instanceof \ArrayAccess && isset($object[$arrayItem])) ) { if ($isDefinedTest) { @@ -604,7 +604,7 @@ abstract class Template implements \Twig_TemplateInterface // object property if (self::METHOD_CALL !== $type && !$object instanceof self) { // \Twig\Template does not have public properties, and we don't want to allow access to internal ones - if (isset($object->$item) || \array_key_exists((string) $item, $object)) { + if (isset($object->$item) || \array_key_exists((string) $item, (array) $object)) { if ($isDefinedTest) { return true; }