diff --git a/.appveyor.yml b/.appveyor.yml index 2aa49e7ed6a1e..9d863ffb3557f 100644 --- a/.appveyor.yml +++ b/.appveyor.yml @@ -10,18 +10,18 @@ init: - SET PATH=c:\php;%PATH% - SET COMPOSER_NO_INTERACTION=1 - SET SYMFONY_DEPRECATIONS_HELPER=strict - - SET "SYMFONY_REQUIRE=>=4.2" + - SET "SYMFONY_REQUIRE=>=4.4" - SET ANSICON=121x90 (121x90) - SET SYMFONY_PHPUNIT_DISABLE_RESULT_CACHE=1 - REG ADD "HKEY_CURRENT_USER\Software\Microsoft\Command Processor" /v DelayedExpansion /t REG_DWORD /d 1 /f install: - mkdir c:\php && cd c:\php - - appveyor DownloadFile https://github.com/symfony/binary-utils/releases/download/v0.1/php-7.1.3-Win32-VC14-x86.zip - - 7z x php-7.1.3-Win32-VC14-x86.zip -y >nul + - appveyor DownloadFile https://github.com/symfony/binary-utils/releases/download/v0.1/php-7.2.5-Win32-VC15-x86.zip + - 7z x php-7.2.5-Win32-VC15-x86.zip -y >nul - cd ext - - appveyor DownloadFile https://github.com/symfony/binary-utils/releases/download/v0.1/php_apcu-5.1.8-7.1-ts-vc14-x86.zip - - 7z x php_apcu-5.1.8-7.1-ts-vc14-x86.zip -y >nul + - appveyor DownloadFile https://github.com/symfony/binary-utils/releases/download/v0.1/php_apcu-5.1.17-7.2-ts-vc15-x86.zip + - 7z x php_apcu-5.1.17-7.2-ts-vc15-x86.zip -y >nul - cd .. - copy /Y php.ini-development php.ini-min - echo memory_limit=-1 >> php.ini-min diff --git a/.github/patch-types.php b/.github/patch-types.php index ca33ef47a61ee..e09e5bbbf4dd8 100644 --- a/.github/patch-types.php +++ b/.github/patch-types.php @@ -7,15 +7,6 @@ require __DIR__.'/../.phpunit/phpunit-8.3-0/vendor/autoload.php'; -file_put_contents(__DIR__.'/../vendor/autoload.php', preg_replace('/^return (Composer.*);/m', <<<'EOTXT' -$loader = \1; -$loader->addClassMap(['Symfony\Component\Debug\Exception\FlattenException' => \dirname(__DIR__).'/src/Symfony/Component/Debug/Exception/FlattenException.php']); - -return $loader; - -EOTXT -, file_get_contents(__DIR__.'/../vendor/autoload.php'))); - $loader = require __DIR__.'/../vendor/autoload.php'; Symfony\Component\ErrorHandler\DebugClassLoader::enable(); @@ -26,7 +17,6 @@ case false !== strpos($file, '/src/Symfony/Bridge/PhpUnit/'): case false !== strpos($file, '/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Validation/Article.php'): case false !== strpos($file, '/src/Symfony/Component/Config/Tests/Fixtures/BadParent.php'): - case false !== strpos($file, '/src/Symfony/Component/Debug/Tests/Fixtures/'): case false !== strpos($file, '/src/Symfony/Component/DependencyInjection/Tests/Compiler/OptionalServiceClass.php'): case false !== strpos($file, '/src/Symfony/Component/DependencyInjection/Tests/Fixtures/ParentNotExists.php'): case false !== strpos($file, '/src/Symfony/Component/DependencyInjection/Tests/Fixtures/Prototype/BadClasses/MissingParent.php'): diff --git a/.php_cs.dist b/.php_cs.dist index e492bd6cd64db..3f0e86f4c38d8 100644 --- a/.php_cs.dist +++ b/.php_cs.dist @@ -39,7 +39,6 @@ return PhpCsFixer\Config::create() // test template ->notPath('Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_name_entry_label.html.php') // explicit trigger_error tests - ->notPath('Symfony/Component/Debug/Tests/DebugClassLoaderTest.php') ->notPath('Symfony/Component/ErrorHandler/Tests/DebugClassLoaderTest.php') ) ; diff --git a/.travis.yml b/.travis.yml index 691f8ee2d6d7d..4638be740549b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -17,7 +17,7 @@ addons: env: global: - - MIN_PHP=7.1.3 + - MIN_PHP=7.2.5 - SYMFONY_PROCESS_PHP_TEST_BINARY=~/.phpenv/shims/php - MESSENGER_AMQP_DSN=amqp://localhost/%2f/messages - MESSENGER_REDIS_DSN=redis://127.0.0.1:7006/messages @@ -25,8 +25,8 @@ env: matrix: include: - - php: 7.1 - env: php_extra="7.2 7.4snapshot" + - php: 7.2 + env: php_extra="7.4snapshot" - php: 7.3 env: deps=high - php: 7.4snapshot @@ -207,7 +207,6 @@ install: if [[ ! $deps ]]; then php .github/build-packages.php HEAD^ src/Symfony/Bridge/PhpUnit src/Symfony/Contracts - composer remove --dev --no-update paragonie/sodium_compat else export SYMFONY_DEPRECATIONS_HELPER=weak && cp composer.json composer.json.orig && @@ -242,7 +241,7 @@ install: - | # Install symfony/flex if [[ $deps = low ]]; then - export SYMFONY_REQUIRE='>=2.3' + export SYMFONY_REQUIRE='>=3.4' else export SYMFONY_REQUIRE=">=$SYMFONY_VERSION" fi @@ -274,7 +273,7 @@ install: (cd src/Symfony/Component/HttpFoundation; mv composer.bak composer.json) COMPONENTS=$(git diff --name-only src/ | grep composer.json || true) - if [[ $COMPONENTS && $LEGACY && $TRAVIS_PULL_REQUEST != false ]]; then + if [[ $COMPONENTS && $LEGACY && $TRAVIS_BRANCH != master && $TRAVIS_PULL_REQUEST != false ]]; then export FLIP='🙃' SYMFONY_VERSION=$(echo $SYMFONY_VERSION | awk '{print $1 - 1}') echo -e "\\n\\e[33;1mChecking out Symfony $SYMFONY_VERSION and running tests with patched components as deps\\e[0m" diff --git a/CHANGELOG-5.0.md b/CHANGELOG-5.0.md new file mode 100644 index 0000000000000..255b7812dc71d --- /dev/null +++ b/CHANGELOG-5.0.md @@ -0,0 +1,315 @@ +CHANGELOG for 5.0.x +=================== + +This changelog references the relevant changes (bug and security fixes) done +in 5.0 minor versions. + +To get the diff for a specific change, go to https://github.com/symfony/symfony/commit/XXX where XXX is the change hash +To get the diff between two versions, go to https://github.com/symfony/symfony/compare/v5.0.0...v5.0.1 + +* 5.0.0-RC1 (2019-11-17) + + * bug #34419 [Cache] Disable igbinary on PHP >= 7.4 (nicolas-grekas) + * bug #34347 [Messenger] Perform no deep merging of bus middleware (vudaltsov) + * bug #34366 [HttpFoundation] Allow redirecting to URLs that contain a semicolon (JayBizzle) + * feature #34405 [HttpFoundation] Added possibility to configure expiration time in redis session handler (mantulo) + * bug #34397 [FrameworkBundle] Remove project dir from Translator cache vary scanned directories (fancyweb) + * bug #34384 [DoctrineBridge] Improve queries parameters display in Profiler (fancyweb) + * bug #34408 [Cache] catch exceptions when using PDO directly (xabbuh) + * bug #34411 [HttpKernel] Flatten "exception" controller argument if not typed (chalasr) + * bug #34410 [HttpFoundation] Fix MySQL column type definition. (jbroutier) + * bug #34403 [Cache] Redis Tag Aware warn on wrong eviction policy (andrerom) + * bug #34400 [HttpKernel] collect bundle classes, not paths (nicolas-grekas) + * bug #34398 [Config] fix id-generation for GlobResource (nicolas-grekas) + * bug #34404 [HttpClient] fix HttpClientDataCollector (nicolas-grekas) + * bug #34396 [Finder] Allow ssh2 stream wrapper for sftp (damienalexandre) + * bug #34383 [DI] Use reproducible entropy to generate env placeholders (nicolas-grekas) + * bug #34389 [WebProfilerBundle] add FrameworkBundle requirement (xabbuh) + * bug #34381 [WebProfilerBundle] Require symfony/twig-bundle (fancyweb) + * bug #34358 [Security] always check the token on non-lazy firewalls (nicolas-grekas, lyrixx) + * bug #34390 [FrameworkBundle] fix wiring of httplug client (nicolas-grekas) + * bug #34369 [FrameworkBundle] Disallow WebProfilerBundle < 4.4 (derrabus) + * bug #34370 [DI] fix detecting singly implemented interfaces (nicolas-grekas) + +* 5.0.0-BETA2 (2019-11-13) + + * bug #34344 [Console] Constant STDOUT might be undefined (nicolas-grekas) + * bug #34348 [Serializer] Fix ProblemNormalizer signature mismatch (chalasr) + * security #cve-2019-18886 [Security\Core] throw AccessDeniedException when switch user fails (nicolas-grekas) + * security #cve-2019-18888 [Mime] fix guessing mime-types of files with leading dash (nicolas-grekas) + * security #cve-2019-11325 [VarExporter] fix exporting some strings (nicolas-grekas) + * security #cve-2019-18889 [Cache] forbid serializing AbstractAdapter and TagAwareAdapter instances (nicolas-grekas) + * security #cve-2019-18888 [HttpFoundation] fix guessing mime-types of files with leading dash (nicolas-grekas) + * security #cve-2019-18887 [HttpKernel] Use constant time comparison in UriSigner (stof) + +* 5.0.0-BETA1 (2019-11-12) + + * feature #34333 Revert "feature #34329 [ExpressionLanguage] add XOR operator (ottaviano)" (nicolas-grekas) + * feature #34332 Allow \Throwable $previous everywhere (fancyweb) + * feature #34329 [ExpressionLanguage] add XOR operator (ottaviano) + * feature #34312 [ErrorHandler] merge and remove the ErrorRenderer component (nicolas-grekas, yceruto) + * feature #34309 [HttpKernel] make ExceptionEvent able to propagate any throwable (nicolas-grekas) + * feature #33497 [Contracts] Add parameter type declarations to contracts (derrabus) + * feature #34139 [Security] Add migrating encoder configuration (chalasr) + * feature #32194 [HttpFoundation] Add a way to anonymize IPs (Seldaek) + * feature #34252 [Console] Add support for NO_COLOR env var (Seldaek) + * feature #34295 [DI][FrameworkBundle] add EnvVarLoaderInterface - remove SecretEnvVarProcessor (nicolas-grekas) + * feature #31310 [DependencyInjection] Added option `ignore_errors: not_found` for imported config files (pulzarraider) + * feature #34216 [HttpClient] allow arbitrary JSON values in requests (pschultz) + * feature #31977 Add handling for delayed message to redis transport (alexander-schranz) + * feature #34217 [Messenger] use events consistently in worker (Tobion) + * feature #33065 Deprecate things that prevent \Throwable from bubbling down (fancyweb) + * feature #34184 [VarDumper] display the method we're in when dumping stack traces (nicolas-grekas) + * feature #33732 [Console] Rename some methods related to redraw frequency (javiereguiluz) + * feature #31587 [Routing][Config] Allow patterns of resources to be excluded from config loading (tristanbes) + * feature #32256 [DI] Add compiler pass and command to check that services wiring matches type declarations (alcalyn, GuilhemN, nicolas-grekas) + * feature #32061 Add new Form WeekType (dFayet) + * feature #33954 Form theme: support Bootstrap 4 custom switches (romaricdrigon) + * feature #33854 [DI] Add ability to choose behavior of decorations on non existent decorated services (mtarld) + * feature #34185 [Messenger] extract worker logic to listener and get rid of SendersLocatorInterface::getSenderByAlias (Tobion) + * feature #34156 Adding DoctrineClearEntityManagerWorkerSubscriber to reset EM in worker (weaverryan) + * feature #34133 [Cache] add DeflateMarshaller - remove phpredis compression (nicolas-grekas) + * feature #34177 [HttpFoundation][FrameworkBundle] allow configuring the session handler with a DSN (nicolas-grekas) + * feature #32107 [Validator] Add AutoMapping constraint to enable or disable auto-validation (dunglas) + * feature #34170 Re-allow to use "tagged" in service definitions (dunglas) + * feature #34043 [Lock] Add missing lock connection string in FrameworkExtension (jderusse) + * feature #34057 [Lock][Cache] Allows URL DSN in PDO adapters (jderusse) + * feature #34151 [DomCrawler] normalizeWhitespace should be true by default (dunglas) + * feature #34020 [Security] Allow to stick to a specific password hashing algorithm (chalasr) + * feature #34141 Slack notifier actions (fabpot) + * feature #34131 [FrameworkBundle] Remove suffix convention when using env vars to override secrets from the vault (nicolas-grekas) + * feature #34051 [HttpClient] allow option "buffer" to be a stream resource (nicolas-grekas) + * feature #34028 [ExpressionLanguage][Lexer] Exponential format for number (tigr1991) + * feature #34069 [Messenger] Removing "sync" transport and replacing it with config trick (weaverryan) + * feature #34014 [DI] made the `env(base64:...)` processor able to decode base64url (nicolas-grekas) + * feature #34044 [HttpClient] Add a canceled state to the ResponseInterface (Toflar) + * feature #33997 [FrameworkBundle] Add `secrets:*` commands and `env(secret:...)` processor to deal with secrets seamlessly (Tobion, jderusse, nicolas-grekas) + * feature #34013 [DI] add `LazyString` for lazy computation of string values injected into services (nicolas-grekas) + * feature #33961 [TwigBridge] Add show-deprecations option to the lint:twig command (yceruto) + * feature #33973 [HttpClient] add HttpClient::createForBaseUri() (nicolas-grekas) + * feature #33980 [HttpClient] try using php-http/discovery when nyholm/psr7 is not installed (nicolas-grekas) + * feature #33967 [Mailer] Add Message-Id to SentMessage when sending an email (fabpot) + * feature #33896 [Serializer][CSV] Add context options to handle BOM (malarzm) + * feature #33883 [Mailer] added ReplyTo option for PostmarkApiTransport (pierregaste) + * feature #33053 [ErrorHandler] Rework fatal errors (fancyweb) + * feature #33939 [Cache] add TagAwareMarshaller to optimize data storage when using AbstractTagAwareAdapter (nicolas-grekas) + * feature #33941 Keeping backward compatibility with legacy FlattenException usage (yceruto) + * feature #33851 [EventDispatcher] Allow to omit the event name when registering listeners (derrabus) + * feature #33461 [Cache] Improve RedisTagAwareAdapter invalidation logic & requirements (andrerom) + * feature #33779 [DI] enable improved syntax for defining method calls in Yaml (nicolas-grekas) + * feature #33743 [HttpClient] Async HTTPlug client (Nyholm) + * feature #33856 [Messenger] Allow to configure the db index on Redis transport (chalasr) + * feature #33881 [VarDumper] Added a support for casting Ramsey/Uuid (lyrixx) + * feature #33687 Notifier Component (fabpot) + * feature #33861 [CssSelector] Support *:only-of-type (jakzal) + * feature #33793 [EventDispatcher] A compiler pass for aliased userland events (derrabus) + * feature #33791 [Form] Added CountryType option for using alpha3 country codes (creiner) + * feature #33628 [DependencyInjection] added Ability to define a priority method for tagged service (lyrixx) + * feature #33768 [String] Introduce a locale-aware Slugger in the String component (tgalopin) + * feature #33775 [Console] Add deprecation message for non-int statusCode (jschaedl) + * feature #33783 [WebProfilerBundle] Try to display the most useful panel by default (fancyweb) + * feature #33701 [HttpKernel] wrap compilation of the container in an opportunistic lock (nicolas-grekas) + * feature #33789 [Serializer] Deprecate the XmlEncoder::TYPE_CASE_ATTRIBUTES constant (pierredup) + * feature #31446 [VarDumper] Output the location of calls to dump() (ktherage) + * feature #33412 [Console] Do not leak hidden console commands (m-vo) + * feature #33676 [Security] add "anonymous: lazy" mode to firewalls (nicolas-grekas) + * feature #32440 [DomCrawler] add a normalizeWhitespace argument to text() method (Simperfit) + * feature #33148 [Intl] Excludes locale from language codes (split localized language names) (ro0NL) + * feature #31202 [FrameworkBundle] WebTestCase KernelBrowser::getContainer null return type (Simperfit) + * feature #33038 [ErrorHandler] Forward \Throwable (fancyweb) + * feature #33574 [Http][DI] Replace REMOTE_ADDR in trusted proxies with the current REMOTE_ADDR (mcfedr) + * feature #33553 [String] a new component for object-oriented strings management with an abstract unit system (nicolas-grekas, hhamon, gharlan) + * feature #33113 [Messenger][DX] Display real handler if handler is wrapped (DavidBadura) + * feature #33128 [FrameworkBundle] Sort tagged services (krome162504) + * feature #33658 [Yaml] fix parsing inline YAML spanning multiple lines (xabbuh) + * feature #33698 [HttpKernel] compress files generated by the profiler (nicolas-grekas) + * feature #33317 [Messenger] Added support for `from_transport` attribute on `messenger.message_handler` tag (ruudk) + * feature #33584 [Security] Deprecate isGranted()/decide() on more than one attribute (wouterj) + * feature #33663 [Security] Make stateful firewalls turn responses private only when needed (nicolas-grekas) + * feature #33609 [Form][SubmitType] Add "validate" option (fancyweb) + * feature #33621 Revert "feature #33507 [WebProfiler] Deprecated intercept_redirects in 4.4 (dorumd)" (lyrixx) + * feature #33635 [FrameworkBundle] Cleanup (yceruto) + * feature #33605 [Twig] Add NotificationEmail (fabpot) + * feature #33623 [DependencyInjection] Allow binding iterable and tagged services (lyrixx) + * feature #33507 [WebProfiler] Deprecated intercept_redirects in 4.4 (dorumd) + * feature #33579 Adding .gitattributes to remove Tests directory from "dist" (Nyholm) + * feature #33562 [Mailer] rename SmtpEnvelope to Envelope (xabbuh) + * feature #33565 [Mailer] Rename an exception class (fabpot) + * feature #33516 [Cache] Added reserved characters constant for CacheItem (andyexeter) + * feature #33503 [SecurityBundle] Move Anonymous DI integration to new AnonymousFactory (wouterj) + * feature #33535 [WebProfilerBundle] Assign automatic colors to custom Stopwatch categories (javiereguiluz) + * feature #32565 [HttpClient] Allow enabling buffering conditionally with a Closure (rjwebdev) + * feature #32032 [DI] generate preload.php file for PHP 7.4 in cache folder (nicolas-grekas) + * feature #33117 [FrameworkBundle] Added --sort option for TranslationUpdateCommand (k0d3r1s) + * feature #32832 [Serializer] Allow multi-dimenstion object array in AbstractObjectNormalizer (alediator) + * feature #33189 New welcome page on startup for 4.4 LTS & 5.0 (yceruto) + * feature #33295 [OptionsResolver] Display full nested option hierarchy in exceptions (fancyweb) + * feature #33486 [VarDumper] Display fully qualified title (pavinthan, nicolas-grekas) + * feature #33496 Deprecated not passing dash symbol (-) to STDIN commands (yceruto) + * feature #32742 [Console] Added support for definition list and horizontal table (lyrixx) + * feature #33494 [Mailer] Change DSN syntax (fabpot) + * feature #33471 [Mailer] Check email validity before opening an SMTP connection (fabpot) + * feature #31177 #21571 Comparing roles to detected that users has changed (oleg-andreyev) + * feature #33459 [Validator] Deprecated CacheInterface in favor of PSR-6 (derrabus) + * feature #33271 Added new ErrorController + Preview and enabling there the error renderer mechanism (yceruto) + * feature #33454 [Mailer] Improve an exception when trying to send a RawMessage without an Envelope (fabpot) + * feature #33327 [ErrorHandler] Registering basic exception handler for late failures (yceruto) + * feature #33446 [TwigBridge] lint all templates from configured Twig paths if no argument was provided (yceruto) + * feature #33409 [Mailer] Add support for multiple mailers (fabpot) + * feature #33424 [Mailer] Change the DSN semantics (fabpot) + * feature #33352 [Security] drop support for non-boolean return values from checkCredentials() (xabbuh) + * feature #33319 Allow configuring class names through methods instead of class parameters in Doctrine extensions (alcaeus) + * feature #33283 [ErrorHandler] make DebugClassLoader able to add return type declarations (nicolas-grekas) + * feature #33323 [TwigBridge] Throw an exception when one uses email as a context variable in a TemplatedEmail (fabpot) + * feature #33308 [SecurityGuard] Deprecate returning non-boolean values from checkCredentials() (derrabus) + * feature #33217 [FrameworkBundle][DX] Improving the redirect config when using RedirectController (yceruto) + * feature #33015 [HttpClient] Added TraceableHttpClient and WebProfiler panel (jeremyFreeAgent) + * feature #33091 [Mime] Add Address::fromString (gisostallenberg) + * feature #33144 [DomCrawler] Added Crawler::matches(), ::closest(), ::outerHtml() (lyrixx) + * feature #33152 Mark all dispatched event classes as final (Tobion) + * feature #33258 [HttpKernel] deprecate global dir to load resources from (Tobion) + * feature #33272 [Translation] deprecate support for null locales (xabbuh) + * feature #33269 [TwigBridge] Mark all classes extending twig as @final (fabpot) + * feature #33270 [Mime] Remove NamedAddress (fabpot) + * feature #33169 [HttpFoundation] Precalculate session expiry timestamp (azjezz) + * feature #33237 [Mailer] Remove the auth mode DSN option and support in the eSMTP transport (fabpot) + * feature #33233 [Mailer] Simplify the way TLS/SSL/STARTTLS work (fabpot) + * feature #32360 [Monolog] Added ElasticsearchLogstashHandler (lyrixx) + * feature #32489 [Messenger] Allow exchange type headers binding (CedrickOka) + * feature #32783 [Messenger] InMemoryTransport handle acknowledged and rejected messages (tienvx) + * feature #33098 added `Process::getLastOutputTime()` method (connorhu) + * feature #33155 [ErrorHandler] Added call() method utility to turns any PHP error into \ErrorException (yceruto) + * feature #33203 [Mailer] Add support for the queued flag in the EmailCount assertion (fabpot) + * feature #30323 [ErrorHandler] trigger deprecation in DebugClassLoader when child class misses a return type (fancyweb, nicolas-grekas) + * feature #33137 [DI] deprecate support for non-object services (nicolas-grekas) + * feature #32845 [HttpKernel][FrameworkBundle] Add alternative convention for bundle directories (yceruto) + * feature #32548 [Translation] XliffLintCommand: allow .xliff file extension (codegain) + * feature #28363 [Serializer] Encode empty objects as objects, not arrays (mcfedr) + * feature #33122 [WebLink] implement PSR-13 directly (nicolas-grekas) + * feature #33078 Add compatibility trait for PHPUnit constraint classes (alcaeus) + * feature #32988 [Intl] Support ISO 3166-1 Alpha-3 country codes (terjebraten-certua) + * feature #32598 [FrameworkBundle][Routing] Private service route loaders (fancyweb) + * feature #32486 [DoctrineBridge] Invokable event listeners (fancyweb) + * feature #31083 [Validator] Allow objects implementing __toString() to be used as violation messages (mdlutz24) + * feature #32122 [HttpFoundation] deprecate HeaderBag::get() returning an array and add all($key) instead (Simperfit) + * feature #32807 [HttpClient] add "max_duration" option (fancyweb) + * feature #31546 [Dotenv] Use default value when referenced variable is not set (j92) + * feature #32930 [Mailer][Mime] Add PHPUnit constraints and assertions for the Mailer (fabpot) + * feature #32912 [Mailer] Add support for the profiler (fabpot) + * feature #32940 [PhpUnitBridge] Add polyfill for PhpUnit namespace (jderusse) + * feature #31843 [Security] add support for opportunistic password migrations (nicolas-grekas) + * feature #32824 [Ldap] Add security LdapUser and provider (chalasr) + * feature #32922 [PhpUnitBridge] make the bridge act as a polyfill for newest PHPUnit features (nicolas-grekas) + * feature #32927 [Mailer] Add message events logger (fabpot) + * feature #32916 [Mailer] Add a name to the transports (fabpot) + * feature #32917 [Mime] Add AbstractPart::asDebugString() (fabpot) + * feature #32543 [FrameworkBundle] add config translator cache_dir (Raulnet) + * feature #32669 [Yaml] Add flag to dump NULL as ~ (OskarStark) + * feature #32896 [Mailer] added debug info to TransportExceptionInterface (fabpot) + * feature #32817 [DoctrineBridge] Deprecate RegistryInterface (Koc) + * feature #32504 [ErrorRenderer] Add DebugCommand for easy debugging and testing (yceruto) + * feature #32581 [DI] Allow dumping the container in one file instead of many files (nicolas-grekas) + * feature #32762 [Form][DX] derive default timezone from reference_date option when possible (yceruto) + * feature #32745 [Messenger][Profiler] Attempt to give more useful source info when using HandleTrait (ogizanagi) + * feature #32680 [Messenger][Profiler] Collect the stamps at the end of dispatch (ogizanagi) + * feature #32683 [VarDumper] added support for Imagine/Image (lyrixx) + * feature #32749 [Mailer] Make transport factory test case public (Koc) + * feature #32718 [Form] use a reference date to handle times during DST (xabbuh) + * feature #32637 [ErrorHandler] Decouple from ErrorRenderer component (yceruto) + * feature #32609 [Mailer][DX][RFC] Rename mailer bridge transport classes (Koc) + * feature #32587 [Form][Validator] Generate accept attribute with file constraint and mime types option (Coosos) + * feature #32658 [Form] repeat preferred choices in list of all choices (Seb33300, xabbuh) + * feature #32698 [WebProfilerBundle] mark all classes as internal (Tobion) + * feature #32695 [WebProfilerBundle] Decoupling TwigBundle and using the new ErrorRenderer mechanism (yceruto) + * feature #31398 [TwigBundle] Deprecating error templates for non-html formats and using ErrorRenderer as fallback (yceruto) + * feature #32582 [Routing] Deprecate ServiceRouterLoader and ObjectRouteLoader in favor of ContainerLoader and ObjectLoader (fancyweb) + * feature #32661 [ErrorRenderer] Improving the exception page provided by HtmlErrorRenderer (yceruto) + * feature #32332 [DI] Move non removing compiler passes to after removing passes (alexpott) + * feature #32475 [Process] Deprecate Process::inheritEnvironmentVariables() (ogizanagi) + * feature #32583 [Mailer] Logger vs debug mailer (fabpot) + * feature #32471 Add a new ErrorHandler component (mirror of the Debug component) (yceruto) + * feature #32463 [VarDumper] Allow to configure VarDumperTestTrait casters & flags (ogizanagi) + * feature #31946 [Mailer] Extract transport factory and allow create custom transports (Koc) + * feature #31194 [PropertyAccess] Improve errors when trying to find a writable property (pierredup) + * feature #32435 [Validator] Add a new constraint message when there is both min and max (Lctrs) + * feature #32470 Rename ErrorCatcher to ErrorRenderer (rendering part only) (yceruto) + * feature #32462 [WebProfilerBundle] Deprecating templateExists method (yceruto) + * feature #32458 Remove support for Twig 1.x (fabpot) + * feature #32446 [Lock] rename and deprecate Factory into LockFactory (Simperfit) + * feature #31975 Dynamic bundle assets (garak) + * feature #32429 [VarDumper] Let browsers trigger their own search on double CMD/CTRL + F (ogizanagi) + * feature #32198 [Lock] Split "StoreInterface" into multiple interfaces with less responsability (Simperfit) + * feature #31511 [Validator] Allow to use property paths to get limits in range constraint (Lctrs) + * feature #32424 [Console] don't redraw progress bar more than every 100ms by default (nicolas-grekas) + * feature #27905 [MonologBridge] Monolog 2 compatibility (derrabus) + * feature #32418 [Console] Added Application::reset() (lyrixx) + * feature #31217 [WebserverBundle] Deprecate the bundle in favor of symfony local server (Simperfit) + * feature #31554 [SECURITY] AbstractAuthenticationListener.php error instead info. Rebase of #28462 (berezuev) + * feature #32284 [Cache] Add argument $prefix to AdapterInterface::clear() (nicolas-grekas) + * feature #32423 [ServerBundle] Display all logs by default (lyrixx) + * feature #26339 [Console] Add ProgressBar::preventRedrawFasterThan() and forceRedrawSlowerThan() methods (ostrolucky) + * feature #31269 [Translator] Dump native plural formats to po files (Stadly) + * feature #31560 [Ldap][Security] LdapBindAuthenticationProvider does not bind before search query (Simperfit) + * feature #31626 [Console] allow answer to be trimmed by adding a flag (Simperfit) + * feature #31876 [WebProfilerBundle] Add clear button to ajax tab (Matts) + * feature #32415 [Translation] deprecate passing a null locale (Simperfit) + * feature #32290 [HttpClient] Add $response->toStream() to cast responses to regular PHP streams (nicolas-grekas) + * feature #32402 [Intl] Exclude root language (ro0NL) + * feature #32295 [FrameworkBundle] Add autowiring alias for PSR-14 (nicolas-grekas) + * feature #32390 [DependencyInjection] Deprecated passing Parameter instances as class name to Definition (derrabus) + * feature #32106 [FrameworkBundle] Use default_locale as default value for translator.fallbacks (dunglas) + * feature #32294 [FrameworkBundle] Allow creating chained cache pools by providing several adapters (nicolas-grekas) + * feature #32373 [Validator] Change Length::$allowEmptyString default to false & make it optional (ogizanagi) + * feature #32207 [FrameworkBundle] Allow to use the BrowserKit assertions with Panther and API Platform's test client (dunglas) + * feature #32344 [HttpFoundation][HttpKernel] Improving the request/response format autodetection (yceruto) + * feature #32231 [HttpClient] Add support for NTLM authentication (nicolas-grekas) + * feature #32265 [Validator] deprecate non-string constraint violation codes (xabbuh) + * feature #31528 [Validator] Add a Length::$allowEmptyString option to reject empty strings (ogizanagi) + * feature #32081 [WIP][Mailer] Overwrite envelope sender and recipients from config (Devristo) + * feature #32255 [HttpFoundation] Drop support for ApacheRequest (lyrixx) + * feature #31825 [Messenger] Added support for auto trimming of redis streams (Toflar) + * feature #32277 Remove @experimental annotations (fabpot) + * feature #30981 [Mime] S/MIME Support (sstok) + * feature #32180 [Lock] add an InvalidTTLException to be more accurate (Simperfit) + * feature #32241 [PropertyAccess] Deprecate null as allowed value for defaultLifetime argument in createCache method (jschaedl) + * feature #32221 [ErrorCatcher] Make IDEs and static analysis tools happy (fabpot) + * feature #32227 Rename the ErrorHandler component to ErrorCatcher (fabpot) + * feature #31065 Add ErrorHandler component (yceruto) + * feature #32126 [Process] Allow writing portable "prepared" command lines (Simperfit) + * feature #31996 Add return types in final classes (dFayet) + * feature #31532 [Ldap] Add users extraFields in ldap component (Simperfit) + * feature #32104 Add autowiring for HTTPlug (nicolas-grekas) + * feature #32130 [Form] deprecate int/float for string input in NumberType (xabbuh) + * feature #31547 [Ldap] Add exception for mapping ldap errors (Simperfit) + * feature #31764 [FrameworkBundle] add attribute stamps (walidboughdiri) + * feature #32059 [PhpUnitBridge] Bump PHPUnit 7+8 (ro0NL) + * feature #32041 [Validator] Deprecate unused arg in ExpressionValidator (ogizanagi) + * feature #31287 [Config] Introduce find method in ArrayNodeDefinition to ease configuration tree manipulation (jschaedl) + * feature #31959 [DomCrawler][Feature][DX] Add Form::getName() method (JustBlackBird) + * feature #32026 [VarDumper] caster for HttpClient's response dumps all info (nicolas-grekas) + * feature #31976 [HttpClient] add HttplugClient for compat with libs that need httplug v1 or v2 (nicolas-grekas) + * feature #31956 [Mailer] Changed EventDispatcherInterface dependency from Component to Contracts (Koc) + * feature #31980 [HttpClient] make Psr18Client implement relevant PSR-17 factories (nicolas-grekas) + * feature #31919 [WebProfilerBundle] Select default theme based on user preferences (javiereguiluz) + * feature #31451 [FrameworkBundle] Allow dots in translation domains (jschaedl) + * feature #31321 [DI] deprecates tag !tagged in favor of !tagged_iterator (jschaedl) + * feature #31658 [HTTP Foundation] Deprecate passing argument to method Request::isMethodSafe() (dFayet) + * feature #31597 [Security] add MigratingPasswordEncoder (nicolas-grekas) + * feature #31351 [Validator] Improve TypeValidator to handle array of types (jschaedl) + * feature #31526 [Validator] Add compared value path to violation parameters (ogizanagi) + * feature #31514 Add exception as HTML comment to beginning and end of `exception_full.html.twig` (ruudk) + * feature #31739 [FrameworkBundle] Add missing BC layer for deprecated ControllerNameParser injections (chalasr) + * feature #31831 [HttpClient] add $response->cancel() (nicolas-grekas) + * feature #31334 [Messenger] Add clear Entity Manager middleware (Koc) + * feature #31800 Removed support for PHP templating everywhere (yceruto) + * feature #31594 [Security] add PasswordEncoderInterface::needsRehash() (nicolas-grekas) + * feature #31821 [FrameworkBundle][TwigBundle] Add missing deprecations for PHP templating layer (yceruto) + * feature #31509 [Monolog] Setup the LoggerProcessor after all other processor (lyrixx) + * feature #31777 [Form] remove deprecated date types options handling (xabbuh) + * feature #31785 [Messenger] Deprecate passing a bus locator to ConsumeMessagesCommand's constructor (chalasr) + * feature #31700 [MonologBridge] RouteProcessor class is now final to ease the the removal of deprecated event (Simperfit) + * feature #31732 [HttpKernel] Make DebugHandlersListener internal (chalasr) + * feature #31539 [HttpKernel] Add lts config (noniagriconomie) + * feature #31437 [Cache] Add Redis Sentinel support (StephenClouse) + * feature #31543 [DI] deprecate short callables in yaml (nicolas-grekas) + diff --git a/UPGRADE-4.4.md b/UPGRADE-4.4.md index 1d1863e4f84a2..4bb7edc5d92da 100644 --- a/UPGRADE-4.4.md +++ b/UPGRADE-4.4.md @@ -168,6 +168,8 @@ Mailer ------ * [BC BREAK] Changed the DSN to use for disabling delivery (using the `NullTransport`) from `smtp://null` to `null://null` (host doesn't matter). + * [BC BREAK] Renamed class `SmtpEnvelope` to `Envelope` and `DelayedSmtpEnvelope` to `DelayedEnvelope`. + * [BC BREAK] Added a required `string $transport` argument to `MessageEvent::__construct`. Messenger --------- @@ -228,7 +230,7 @@ Security **After** ```php - if ($this->authorizationChecker->isGranted(new Expression("has_role('ROLE_USER') or has_role('ROLE_ADMIN')"))) {} + if ($this->authorizationChecker->isGranted(new Expression("is_granted('ROLE_USER') or is_granted('ROLE_ADMIN')"))) {} // or: if ($this->authorizationChecker->isGranted('ROLE_USER') diff --git a/UPGRADE-5.1.md b/UPGRADE-5.1.md new file mode 100644 index 0000000000000..619aefa79cd5d --- /dev/null +++ b/UPGRADE-5.1.md @@ -0,0 +1,13 @@ +UPGRADE FROM 5.0 to 5.1 +======================= + +FrameworkBundle +--------------- + + * Marked `MicroKernelTrait::configureRoutes()` as `@internal` and `@final`. + * Deprecated not overriding `MicroKernelTrait::configureRouting()`. + +Routing +------- + + * Deprecated `RouteCollectionBuilder` in favor of `RoutingConfigurator`. diff --git a/UPGRADE-6.0.md b/UPGRADE-6.0.md new file mode 100644 index 0000000000000..3a3cd85984d03 --- /dev/null +++ b/UPGRADE-6.0.md @@ -0,0 +1,13 @@ +UPGRADE FROM 5.x to 6.0 +======================= + +FrameworkBundle +--------------- + + * Removed `MicroKernelTrait::configureRoutes()`. + * Made `MicroKernelTrait::configureRouting()` abstract. + +Routing +------- + + * Removed `RouteCollectionBuilder`. diff --git a/composer.json b/composer.json index a8d1e6b54c43d..18df5b64655c9 100644 --- a/composer.json +++ b/composer.json @@ -16,21 +16,23 @@ } ], "require": { - "php": "^7.1.3", + "php": "^7.2.5", "ext-xml": "*", "doctrine/event-manager": "~1.0", "doctrine/persistence": "~1.0", - "twig/twig": "^1.41|^2.10|^3.0", + "twig/twig": "^2.10|^3.0", "psr/cache": "~1.0", "psr/container": "^1.0", + "psr/event-dispatcher": "^1.0", "psr/link": "^1.0", "psr/log": "~1.0", - "symfony/contracts": "^1.1.8", + "symfony/contracts": "^2", "symfony/polyfill-ctype": "~1.8", + "symfony/polyfill-intl-grapheme": "~1.0", "symfony/polyfill-intl-icu": "~1.0", "symfony/polyfill-intl-idn": "^1.10", + "symfony/polyfill-intl-normalizer": "~1.0", "symfony/polyfill-mbstring": "~1.0", - "symfony/polyfill-php72": "~1.5", "symfony/polyfill-php73": "^1.11" }, "replace": { @@ -42,7 +44,6 @@ "symfony/console": "self.version", "symfony/css-selector": "self.version", "symfony/dependency-injection": "self.version", - "symfony/debug": "self.version", "symfony/debug-bundle": "self.version", "symfony/doctrine-bridge": "self.version", "symfony/dom-crawler": "self.version", @@ -68,6 +69,7 @@ "symfony/messenger": "self.version", "symfony/mime": "self.version", "symfony/monolog-bridge": "self.version", + "symfony/notifier": "self.version", "symfony/options-resolver": "self.version", "symfony/postmark-mailer": "self.version", "symfony/process": "self.version", @@ -75,7 +77,6 @@ "symfony/property-info": "self.version", "symfony/proxy-manager-bridge": "self.version", "symfony/routing": "self.version", - "symfony/security": "self.version", "symfony/security-core": "self.version", "symfony/security-csrf": "self.version", "symfony/security-guard": "self.version", @@ -84,6 +85,7 @@ "symfony/sendgrid-mailer": "self.version", "symfony/serializer": "self.version", "symfony/stopwatch": "self.version", + "symfony/string": "self.version", "symfony/templating": "self.version", "symfony/translation": "self.version", "symfony/twig-bridge": "self.version", @@ -93,7 +95,6 @@ "symfony/var-exporter": "self.version", "symfony/web-link": "self.version", "symfony/web-profiler-bundle": "self.version", - "symfony/web-server-bundle": "self.version", "symfony/workflow": "self.version", "symfony/yaml": "self.version" }, @@ -109,7 +110,7 @@ "doctrine/doctrine-bundle": "^1.5|^2.0", "guzzlehttp/promises": "^1.3.1", "masterminds/html5": "^2.6", - "monolog/monolog": "^1.25.1", + "monolog/monolog": "^1.25.1|^2", "nyholm/psr7": "^1.0", "ocramius/proxy-manager": "^2.1", "paragonie/sodium_compat": "^1.8", @@ -127,8 +128,7 @@ }, "conflict": { "masterminds/html5": "<2.6", - "monolog/monolog": ">=2", - "phpdocumentor/reflection-docblock": "<3.0||>=3.2.0,<3.2.2", + "phpdocumentor/reflection-docblock": "<3.2.2", "phpdocumentor/type-resolver": "<0.3.0", "ocramius/proxy-manager": "<2.1", "phpunit/phpunit": "<5.4.3" @@ -150,7 +150,10 @@ ] }, "autoload-dev": { - "files": [ "src/Symfony/Component/VarDumper/Resources/functions/dump.php" ] + "files": [ + "src/Symfony/Component/String/Resources/functions.php", + "src/Symfony/Component/VarDumper/Resources/functions/dump.php" + ] }, "repositories": [ { @@ -161,7 +164,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.1-dev" } } } diff --git a/src/Symfony/Bridge/Doctrine/CHANGELOG.md b/src/Symfony/Bridge/Doctrine/CHANGELOG.md index 18885f00b2ec9..69428ea8bf3d3 100644 --- a/src/Symfony/Bridge/Doctrine/CHANGELOG.md +++ b/src/Symfony/Bridge/Doctrine/CHANGELOG.md @@ -1,6 +1,14 @@ CHANGELOG ========= +5.0.0 +----- + + * the `getMetadataDriverClass()` method is abstract and must be implemented by class extending `AbstractDoctrineExtension` + * passing an `IdReader` to the `DoctrineChoiceLoader` when the query cannot be optimized with single id field, throws an exception; pass `null` instead + * not explicitly passing an instance of `IdReader` to `DoctrineChoiceLoader` when it can optimize single id field, will not apply any optimization + * `DoctrineExtractor` now requires an `EntityManagerInterface` on instantiation + 4.4.0 ----- diff --git a/src/Symfony/Bridge/Doctrine/CacheWarmer/ProxyCacheWarmer.php b/src/Symfony/Bridge/Doctrine/CacheWarmer/ProxyCacheWarmer.php index 9bf22357df895..d36b3f9a70bdb 100644 --- a/src/Symfony/Bridge/Doctrine/CacheWarmer/ProxyCacheWarmer.php +++ b/src/Symfony/Bridge/Doctrine/CacheWarmer/ProxyCacheWarmer.php @@ -44,7 +44,7 @@ public function isOptional() /** * {@inheritdoc} */ - public function warmUp($cacheDir) + public function warmUp(string $cacheDir) { foreach ($this->registry->getManagers() as $em) { // we need the directory no matter the proxy cache generation strategy diff --git a/src/Symfony/Bridge/Doctrine/DataCollector/DoctrineDataCollector.php b/src/Symfony/Bridge/Doctrine/DataCollector/DoctrineDataCollector.php index b184a7163d45a..c686af5512944 100644 --- a/src/Symfony/Bridge/Doctrine/DataCollector/DoctrineDataCollector.php +++ b/src/Symfony/Bridge/Doctrine/DataCollector/DoctrineDataCollector.php @@ -46,20 +46,16 @@ public function __construct(ManagerRegistry $registry) /** * Adds the stack logger for a connection. - * - * @param string $name */ - public function addLogger($name, DebugStack $logger) + public function addLogger(string $name, DebugStack $logger) { $this->loggers[$name] = $logger; } /** * {@inheritdoc} - * - * @param \Throwable|null $exception */ - public function collect(Request $request, Response $response/*, \Throwable $exception = null*/) + public function collect(Request $request, Response $response, \Throwable $exception = null) { $queries = []; foreach ($this->loggers as $name => $logger) { diff --git a/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php b/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php index 75ed762febaeb..14f8b6b8b9846 100644 --- a/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php +++ b/src/Symfony/Bridge/Doctrine/DependencyInjection/AbstractDoctrineExtension.php @@ -100,11 +100,8 @@ protected function loadMappingInformation(array $objectManager, ContainerBuilder * Register the alias for this mapping driver. * * Aliases can be used in the Query languages of all the Doctrine object managers to simplify writing tasks. - * - * @param array $mappingConfig - * @param string $mappingName */ - protected function setMappingDriverAlias($mappingConfig, $mappingName) + protected function setMappingDriverAlias(array $mappingConfig, string $mappingName) { if (isset($mappingConfig['alias'])) { $this->aliasMap[$mappingConfig['alias']] = $mappingConfig['prefix']; @@ -116,11 +113,9 @@ protected function setMappingDriverAlias($mappingConfig, $mappingName) /** * Register the mapping driver configuration for later use with the object managers metadata driver chain. * - * @param string $mappingName - * * @throws \InvalidArgumentException */ - protected function setMappingDriverConfig(array $mappingConfig, $mappingName) + protected function setMappingDriverConfig(array $mappingConfig, string $mappingName) { $mappingDirectory = $mappingConfig['dir']; if (!is_dir($mappingDirectory)) { @@ -169,10 +164,8 @@ protected function getMappingDriverBundleConfigDefaults(array $bundleConfig, \Re /** * Register all the collected mapping information with the object manager by registering the appropriate mapping drivers. - * - * @param array $objectManager */ - protected function registerMappingDrivers($objectManager, ContainerBuilder $container) + protected function registerMappingDrivers(array $objectManager, ContainerBuilder $container) { // configure metadata driver for each bundle based on the type of mapping files found if ($container->hasDefinition($this->getObjectManagerElementName($objectManager['name'].'_metadata_driver'))) { @@ -222,11 +215,9 @@ protected function registerMappingDrivers($objectManager, ContainerBuilder $cont /** * Assertion if the specified mapping information is valid. * - * @param string $objectManagerName - * * @throws \InvalidArgumentException */ - protected function assertValidMappingConfiguration(array $mappingConfig, $objectManagerName) + protected function assertValidMappingConfiguration(array $mappingConfig, string $objectManagerName) { if (!$mappingConfig['type'] || !$mappingConfig['dir'] || !$mappingConfig['prefix']) { throw new \InvalidArgumentException(sprintf('Mapping definitions for Doctrine manager "%s" require at least the "type", "dir" and "prefix" options.', $objectManagerName)); @@ -248,11 +239,9 @@ protected function assertValidMappingConfiguration(array $mappingConfig, $object /** * Detects what metadata driver to use for the supplied directory. * - * @param string $dir A directory path - * * @return string|null A metadata driver short name, if one can be detected */ - protected function detectMetadataDriver($dir, ContainerBuilder $container) + protected function detectMetadataDriver(string $dir, ContainerBuilder $container) { $configPath = $this->getMappingResourceConfigDirectory(); $extension = $this->getMappingResourceExtension(); @@ -281,12 +270,9 @@ protected function detectMetadataDriver($dir, ContainerBuilder $container) /** * Loads a configured object manager metadata, query or result cache driver. * - * @param array $objectManager A configured object manager - * @param string $cacheName - * * @throws \InvalidArgumentException in case of unknown driver type */ - protected function loadObjectManagerCacheDriver(array $objectManager, ContainerBuilder $container, $cacheName) + protected function loadObjectManagerCacheDriver(array $objectManager, ContainerBuilder $container, string $cacheName) { $this->loadCacheDriver($cacheName, $objectManager['name'], $objectManager[$cacheName.'_driver'], $container); } @@ -294,15 +280,11 @@ protected function loadObjectManagerCacheDriver(array $objectManager, ContainerB /** * Loads a cache driver. * - * @param string $cacheName The cache driver name - * @param string $objectManagerName The object manager name - * @param array $cacheDriver The cache driver mapping - * * @return string * * @throws \InvalidArgumentException */ - protected function loadCacheDriver($cacheName, $objectManagerName, array $cacheDriver, ContainerBuilder $container) + protected function loadCacheDriver(string $cacheName, string $objectManagerName, array $cacheDriver, ContainerBuilder $container) { $cacheDriverServiceId = $this->getObjectManagerElementName($objectManagerName.'_'.$cacheName); @@ -405,11 +387,9 @@ protected function fixManagersAutoMappings(array $managerConfigs, array $bundles * * @example $name is 'entity_manager' then the result would be 'doctrine.orm.entity_manager' * - * @param string $name - * * @return string */ - abstract protected function getObjectManagerElementName($name); + abstract protected function getObjectManagerElementName(string $name); /** * Noun that describes the mapped objects such as Entity or Document. @@ -437,12 +417,7 @@ abstract protected function getMappingResourceExtension(); /** * The class name used by the various mapping drivers. */ - protected function getMetadataDriverClass(string $driverType): string - { - @trigger_error(sprintf('Not declaring the "%s" method in class "%s" is deprecated since Symfony 4.4. This method will be abstract in Symfony 5.0.', __METHOD__, static::class), E_USER_DEPRECATED); - - return '%'.$this->getObjectManagerElementName('metadata.'.$driverType.'.class%'); - } + abstract protected function getMetadataDriverClass(string $driverType): string; /** * Search for a manager that is declared as 'auto_mapping' = true. diff --git a/src/Symfony/Bridge/Doctrine/DependencyInjection/Security/UserProvider/EntityFactory.php b/src/Symfony/Bridge/Doctrine/DependencyInjection/Security/UserProvider/EntityFactory.php index 352bf79bfbc7e..454c7cc0b9222 100644 --- a/src/Symfony/Bridge/Doctrine/DependencyInjection/Security/UserProvider/EntityFactory.php +++ b/src/Symfony/Bridge/Doctrine/DependencyInjection/Security/UserProvider/EntityFactory.php @@ -33,7 +33,7 @@ public function __construct(string $key, string $providerId) $this->providerId = $providerId; } - public function create(ContainerBuilder $container, $id, $config) + public function create(ContainerBuilder $container, string $id, array $config) { $container ->setDefinition($id, new ChildDefinition($this->providerId)) diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/DoctrineChoiceLoader.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/DoctrineChoiceLoader.php index b2810e16966f2..87c1f8263f877 100644 --- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/DoctrineChoiceLoader.php +++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/DoctrineChoiceLoader.php @@ -47,20 +47,7 @@ public function __construct(ObjectManager $manager, string $class, IdReader $idR $classMetadata = $manager->getClassMetadata($class); if ($idReader && !$idReader->isSingleId()) { - @trigger_error(sprintf('Passing an instance of "%s" to "%s" with an entity class "%s" that has a composite id is deprecated since Symfony 4.3 and will throw an exception in 5.0.', IdReader::class, __CLASS__, $class), E_USER_DEPRECATED); - - // In Symfony 5.0 - // throw new \InvalidArgumentException(sprintf('The second argument `$idReader` of "%s" must be null when the query cannot be optimized because of composite id fields.', __METHOD__)); - } - - if ((5 > \func_num_args() || false !== func_get_arg(4)) && null === $idReader) { - $idReader = new IdReader($manager, $classMetadata); - - if ($idReader->isSingleId()) { - @trigger_error(sprintf('Not explicitly passing an instance of "%s" to "%s" when it can optimize single id entity "%s" has been deprecated in 4.3 and will not apply any optimization in 5.0.', IdReader::class, __CLASS__, $class), E_USER_DEPRECATED); - } else { - $idReader = null; - } + throw new \InvalidArgumentException(sprintf('The second argument `$idReader` of "%s" must be null when the query cannot be optimized because of composite id fields.', __METHOD__)); } $this->manager = $manager; @@ -72,7 +59,7 @@ public function __construct(ObjectManager $manager, string $class, IdReader $idR /** * {@inheritdoc} */ - public function loadChoiceList($value = null) + public function loadChoiceList(callable $value = null) { if ($this->choiceList) { return $this->choiceList; @@ -88,7 +75,7 @@ public function loadChoiceList($value = null) /** * {@inheritdoc} */ - public function loadValuesForChoices(array $choices, $value = null) + public function loadValuesForChoices(array $choices, callable $value = null) { // Performance optimization if (empty($choices)) { @@ -120,7 +107,7 @@ public function loadValuesForChoices(array $choices, $value = null) /** * {@inheritdoc} */ - public function loadChoicesForValues(array $values, $value = null) + public function loadChoicesForValues(array $values, callable $value = null) { // Performance optimization // Also prevents the generation of "WHERE id IN ()" queries through the diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityLoaderInterface.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityLoaderInterface.php index e36043af63cb8..8eb5a84484503 100644 --- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityLoaderInterface.php +++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/EntityLoaderInterface.php @@ -28,12 +28,7 @@ public function getEntities(); /** * Returns an array of entities matching the given identifiers. * - * @param string $identifier The identifier field of the object. This method - * is not applicable for fields with multiple - * identifiers. - * @param array $values The values of the identifiers - * * @return array The entities */ - public function getEntitiesByIds($identifier, array $values); + public function getEntitiesByIds(string $identifier, array $values); } diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php index bcba6a4b7e02f..b255c10364651 100644 --- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php +++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/IdReader.php @@ -84,11 +84,9 @@ public function isIntId(): bool * * This method assumes that the object has a single-column ID. * - * @param object $object The object - * * @return mixed The ID value */ - public function getIdValue($object) + public function getIdValue(object $object = null) { if (!$object) { return null; diff --git a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php index 1b880e5064768..488246e6a8eae 100644 --- a/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php +++ b/src/Symfony/Bridge/Doctrine/Form/ChoiceList/ORMQueryBuilderLoader.php @@ -48,7 +48,7 @@ public function getEntities() /** * {@inheritdoc} */ - public function getEntitiesByIds($identifier, array $values) + public function getEntitiesByIds(string $identifier, array $values) { $qb = clone $this->queryBuilder; $alias = current($qb->getRootAliases()); diff --git a/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php b/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php index b7f16a3cd6c14..d72146eede24a 100644 --- a/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php +++ b/src/Symfony/Bridge/Doctrine/Form/DoctrineOrmTypeGuesser.php @@ -36,7 +36,7 @@ public function __construct(ManagerRegistry $registry) /** * {@inheritdoc} */ - public function guessType($class, $property) + public function guessType(string $class, string $property) { if (!$ret = $this->getMetadata($class)) { return new TypeGuess('Symfony\Component\Form\Extension\Core\Type\TextType', [], Guess::LOW_CONFIDENCE); @@ -94,7 +94,7 @@ public function guessType($class, $property) /** * {@inheritdoc} */ - public function guessRequired($class, $property) + public function guessRequired(string $class, string $property) { $classMetadatas = $this->getMetadata($class); @@ -134,7 +134,7 @@ public function guessRequired($class, $property) /** * {@inheritdoc} */ - public function guessMaxLength($class, $property) + public function guessMaxLength(string $class, string $property) { $ret = $this->getMetadata($class); if ($ret && isset($ret[0]->fieldMappings[$property]) && !$ret[0]->hasAssociation($property)) { @@ -155,7 +155,7 @@ public function guessMaxLength($class, $property) /** * {@inheritdoc} */ - public function guessPattern($class, $property) + public function guessPattern(string $class, string $property) { $ret = $this->getMetadata($class); if ($ret && isset($ret[0]->fieldMappings[$property]) && !$ret[0]->hasAssociation($property)) { @@ -167,7 +167,7 @@ public function guessPattern($class, $property) return null; } - protected function getMetadata($class) + protected function getMetadata(string $class) { // normalize class name $class = self::getRealClass(ltrim($class, '\\')); diff --git a/src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php b/src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php index c5f34ce951a21..8589c3bd042b0 100644 --- a/src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php +++ b/src/Symfony/Bridge/Doctrine/Form/Type/DoctrineType.php @@ -50,12 +50,11 @@ abstract class DoctrineType extends AbstractType implements ResetInterface * * For backwards compatibility, objects are cast to strings by default. * - * @param object $choice The object * * @internal This method is public to be usable as callback. It should not * be used in user code. */ - public static function createChoiceLabel($choice): string + public static function createChoiceLabel(object $choice): string { return (string) $choice; } @@ -67,15 +66,14 @@ public static function createChoiceLabel($choice): string * a single-column integer ID. In that case, the value of the field is * the ID of the object. That ID is also used as field name. * - * @param object $choice The object - * @param int|string $key The choice key - * @param string $value The choice value. Corresponds to the object's - * ID here. + * @param int|string $key The choice key + * @param string $value The choice value. Corresponds to the object's + * ID here. * * @internal This method is public to be usable as callback. It should not * be used in user code. */ - public static function createChoiceName($choice, $key, $value): string + public static function createChoiceName(object $choice, $key, string $value): string { return str_replace('-', '_', (string) $value); } @@ -264,12 +262,9 @@ public function configureOptions(OptionsResolver $resolver) /** * Return the default loader object. * - * @param mixed $queryBuilder - * @param string $class - * * @return EntityLoaderInterface */ - abstract public function getLoader(ObjectManager $manager, $queryBuilder, $class); + abstract public function getLoader(ObjectManager $manager, QueryBuilder $queryBuilder, string $class); public function getParent() { diff --git a/src/Symfony/Bridge/Doctrine/Form/Type/EntityType.php b/src/Symfony/Bridge/Doctrine/Form/Type/EntityType.php index 87d131a8c2ed8..2cdd8109138cc 100644 --- a/src/Symfony/Bridge/Doctrine/Form/Type/EntityType.php +++ b/src/Symfony/Bridge/Doctrine/Form/Type/EntityType.php @@ -46,12 +46,9 @@ public function configureOptions(OptionsResolver $resolver) /** * Return the default loader object. * - * @param QueryBuilder $queryBuilder - * @param string $class - * * @return ORMQueryBuilderLoader */ - public function getLoader(ObjectManager $manager, $queryBuilder, $class) + public function getLoader(ObjectManager $manager, QueryBuilder $queryBuilder, string $class) { return new ORMQueryBuilderLoader($queryBuilder); } diff --git a/src/Symfony/Bridge/Doctrine/Logger/DbalLogger.php b/src/Symfony/Bridge/Doctrine/Logger/DbalLogger.php index 27bbd984cb38f..63437920bde1d 100644 --- a/src/Symfony/Bridge/Doctrine/Logger/DbalLogger.php +++ b/src/Symfony/Bridge/Doctrine/Logger/DbalLogger.php @@ -62,11 +62,8 @@ public function stopQuery() /** * Logs a message. - * - * @param string $message A message to log - * @param array $params The context */ - protected function log($message, array $params) + protected function log(string $message, array $params) { $this->logger->debug($message, $params); } diff --git a/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php b/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php index c6d2e52cc1e11..896be36f84540 100644 --- a/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php +++ b/src/Symfony/Bridge/Doctrine/PropertyInfo/DoctrineExtractor.php @@ -11,7 +11,6 @@ namespace Symfony\Bridge\Doctrine\PropertyInfo; -use Doctrine\Common\Persistence\Mapping\ClassMetadataFactory; use Doctrine\Common\Persistence\Mapping\MappingException; use Doctrine\DBAL\Types\Type as DBALType; use Doctrine\ORM\EntityManagerInterface; @@ -33,25 +32,15 @@ class DoctrineExtractor implements PropertyListExtractorInterface, PropertyTypeE private $entityManager; private $classMetadataFactory; - /** - * @param EntityManagerInterface $entityManager - */ - public function __construct($entityManager) + public function __construct(EntityManagerInterface $entityManager) { - if ($entityManager instanceof EntityManagerInterface) { - $this->entityManager = $entityManager; - } elseif ($entityManager instanceof ClassMetadataFactory) { - @trigger_error(sprintf('Injecting an instance of "%s" in "%s" is deprecated since Symfony 4.2, inject an instance of "%s" instead.', ClassMetadataFactory::class, __CLASS__, EntityManagerInterface::class), E_USER_DEPRECATED); - $this->classMetadataFactory = $entityManager; - } else { - throw new \TypeError(sprintf('$entityManager must be an instance of "%s", "%s" given.', EntityManagerInterface::class, \is_object($entityManager) ? \get_class($entityManager) : \gettype($entityManager))); - } + $this->entityManager = $entityManager; } /** * {@inheritdoc} */ - public function getProperties($class, array $context = []) + public function getProperties(string $class, array $context = []) { if (null === $metadata = $this->getMetadata($class)) { return null; @@ -73,7 +62,7 @@ public function getProperties($class, array $context = []) /** * {@inheritdoc} */ - public function getTypes($class, $property, array $context = []) + public function getTypes(string $class, string $property, array $context = []) { if (null === $metadata = $this->getMetadata($class)) { return null; @@ -175,7 +164,7 @@ public function getTypes($class, $property, array $context = []) /** * {@inheritdoc} */ - public function isReadable($class, $property, array $context = []) + public function isReadable(string $class, string $property, array $context = []) { return null; } @@ -183,7 +172,7 @@ public function isReadable($class, $property, array $context = []) /** * {@inheritdoc} */ - public function isWritable($class, $property, array $context = []) + public function isWritable(string $class, string $property, array $context = []) { if ( null === ($metadata = $this->getMetadata($class)) diff --git a/src/Symfony/Bridge/Doctrine/RegistryInterface.php b/src/Symfony/Bridge/Doctrine/RegistryInterface.php deleted file mode 100644 index 17ccace1286f6..0000000000000 --- a/src/Symfony/Bridge/Doctrine/RegistryInterface.php +++ /dev/null @@ -1,96 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bridge\Doctrine; - -use Doctrine\Common\Persistence\ManagerRegistry as ManagerRegistryInterface; -use Doctrine\ORM\EntityManager; - -/** - * References Doctrine connections and entity managers. - * - * @deprecated since Symfony 4.4, use Doctrine\Common\Persistence\ManagerRegistry instead - * - * @author Fabien Potencier - */ -interface RegistryInterface extends ManagerRegistryInterface -{ - /** - * Gets the default entity manager name. - * - * @return string The default entity manager name - */ - public function getDefaultEntityManagerName(); - - /** - * Gets a named entity manager. - * - * @param string $name The entity manager name (null for the default one) - * - * @return EntityManager - */ - public function getEntityManager($name = null); - - /** - * Gets an array of all registered entity managers. - * - * @return array An array of EntityManager instances - */ - public function getEntityManagers(); - - /** - * Resets a named entity manager. - * - * This method is useful when an entity manager has been closed - * because of a rollbacked transaction AND when you think that - * it makes sense to get a new one to replace the closed one. - * - * Be warned that you will get a brand new entity manager as - * the existing one is not usable anymore. This means that any - * other object with a dependency on this entity manager will - * hold an obsolete reference. You can inject the registry instead - * to avoid this problem. - * - * @param string $name The entity manager name (null for the default one) - * - * @return EntityManager - */ - public function resetEntityManager($name = null); - - /** - * Resolves a registered namespace alias to the full namespace. - * - * This method looks for the alias in all registered entity managers. - * - * @param string $alias The alias - * - * @return string The full namespace - * - * @see Configuration::getEntityNamespace - */ - public function getEntityNamespace($alias); - - /** - * Gets all connection names. - * - * @return array An array of connection names - */ - public function getEntityManagerNames(); - - /** - * Gets the entity manager associated with a given class. - * - * @param string $class A Doctrine Entity class name - * - * @return EntityManager|null - */ - public function getEntityManagerForClass($class); -} diff --git a/src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php b/src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php index 64515fac71840..7a6c8327b5d1a 100644 --- a/src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php +++ b/src/Symfony/Bridge/Doctrine/Security/RememberMe/DoctrineTokenProvider.php @@ -48,7 +48,7 @@ public function __construct(Connection $conn) /** * {@inheritdoc} */ - public function loadTokenBySeries($series) + public function loadTokenBySeries(string $series) { // the alias for lastUsed works around case insensitivity in PostgreSQL $sql = 'SELECT class, username, value, lastUsed AS last_used' @@ -68,7 +68,7 @@ public function loadTokenBySeries($series) /** * {@inheritdoc} */ - public function deleteTokenBySeries($series) + public function deleteTokenBySeries(string $series) { $sql = 'DELETE FROM rememberme_token WHERE series=:series'; $paramValues = ['series' => $series]; @@ -79,7 +79,7 @@ public function deleteTokenBySeries($series) /** * {@inheritdoc} */ - public function updateToken($series, $tokenValue, \DateTime $lastUsed) + public function updateToken(string $series, string $tokenValue, \DateTime $lastUsed) { $sql = 'UPDATE rememberme_token SET value=:value, lastUsed=:lastUsed' .' WHERE series=:series'; diff --git a/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php b/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php index 0f396a3958325..17c8b4a328350 100644 --- a/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php +++ b/src/Symfony/Bridge/Doctrine/Security/User/EntityUserProvider.php @@ -48,7 +48,7 @@ public function __construct(ManagerRegistry $registry, string $classOrAlias, str /** * {@inheritdoc} */ - public function loadUserByUsername($username) + public function loadUserByUsername(string $username) { $repository = $this->getRepository(); if (null !== $this->property) { @@ -106,7 +106,7 @@ public function refreshUser(UserInterface $user) /** * {@inheritdoc} */ - public function supportsClass($class) + public function supportsClass(string $class) { return $class === $this->getClass() || is_subclass_of($class, $this->getClass()); } diff --git a/src/Symfony/Bridge/Doctrine/Security/User/UserLoaderInterface.php b/src/Symfony/Bridge/Doctrine/Security/User/UserLoaderInterface.php index 452939fa7934a..d996f71702291 100644 --- a/src/Symfony/Bridge/Doctrine/Security/User/UserLoaderInterface.php +++ b/src/Symfony/Bridge/Doctrine/Security/User/UserLoaderInterface.php @@ -31,9 +31,7 @@ interface UserLoaderInterface * * This method must return null if the user is not found. * - * @param string $username The username - * * @return UserInterface|null */ - public function loadUserByUsername($username); + public function loadUserByUsername(string $username); } diff --git a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php index 0c1a67967d118..3a7fc18058990 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/DependencyInjection/DoctrineExtensionTest.php @@ -37,6 +37,7 @@ protected function setUp(): void 'getObjectManagerElementName', 'getMappingObjectDefaultName', 'getMappingResourceExtension', + 'getMetadataDriverClass', 'load', ]) ->getMock() diff --git a/src/Symfony/Bridge/Doctrine/Tests/Fixtures/BaseUser.php b/src/Symfony/Bridge/Doctrine/Tests/Fixtures/BaseUser.php index aa24cd68943dd..416d5b20bf7b1 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Fixtures/BaseUser.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Fixtures/BaseUser.php @@ -2,9 +2,6 @@ namespace Symfony\Bridge\Doctrine\Tests\Fixtures; -use Symfony\Component\Validator\Constraints as Assert; -use Symfony\Component\Validator\Mapping\ClassMetadata; - /** * Class BaseUser. */ @@ -40,15 +37,4 @@ public function getUsername(): string { return $this->username; } - - public static function loadValidatorMetadata(ClassMetadata $metadata): void - { - $allowEmptyString = property_exists(Assert\Length::class, 'allowEmptyString') ? ['allowEmptyString' => true] : []; - - $metadata->addPropertyConstraint('username', new Assert\Length([ - 'min' => 2, - 'max' => 120, - 'groups' => ['Registration'], - ] + $allowEmptyString)); - } } diff --git a/src/Symfony/Bridge/Doctrine/Tests/Fixtures/DoctrineLoaderEntity.php b/src/Symfony/Bridge/Doctrine/Tests/Fixtures/DoctrineLoaderEntity.php index 06f8674e56d66..8c0b348e3bf3a 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Fixtures/DoctrineLoaderEntity.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Fixtures/DoctrineLoaderEntity.php @@ -14,7 +14,6 @@ use Doctrine\ORM\Mapping as ORM; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Validator\Constraints as Assert; -use Symfony\Component\Validator\Mapping\ClassMetadata; /** * @ORM\Entity @@ -37,11 +36,13 @@ class DoctrineLoaderEntity extends DoctrineLoaderParentEntity /** * @ORM\Column(length=20) + * @Assert\Length(min=5, allowEmptyString=true) */ public $mergedMaxLength; /** * @ORM\Column(length=20) + * @Assert\Length(min=1, max=10, allowEmptyString=true) */ public $alreadyMappedMaxLength; @@ -74,12 +75,4 @@ class DoctrineLoaderEntity extends DoctrineLoaderParentEntity * @Assert\DisableAutoMapping */ public $noAutoMapping; - - public static function loadValidatorMetadata(ClassMetadata $metadata): void - { - $allowEmptyString = property_exists(Assert\Length::class, 'allowEmptyString') ? ['allowEmptyString' => true] : []; - - $metadata->addPropertyConstraint('mergedMaxLength', new Assert\Length(['min' => 5] + $allowEmptyString)); - $metadata->addPropertyConstraint('alreadyMappedMaxLength', new Assert\Length(['min' => 1, 'max' => 10] + $allowEmptyString)); - } } diff --git a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php index 0fa4d5676fda1..c2c720a390d13 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Form/ChoiceList/DoctrineChoiceLoaderTest.php @@ -19,7 +19,6 @@ use Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader; use Symfony\Bridge\Doctrine\Form\ChoiceList\EntityLoaderInterface; use Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader; -use Symfony\Bridge\Doctrine\Tests\Fixtures\SingleIntIdEntity; use Symfony\Component\Form\ChoiceList\ArrayChoiceList; use Symfony\Component\Form\ChoiceList\Factory\ChoiceListFactoryInterface; @@ -377,87 +376,17 @@ public function testLoadChoicesForValuesLoadsOnlyChoicesIfValueIsIdReader() $this->assertSame([$this->obj2], $loader->loadChoicesForValues(['2'], $value)); } - /** - * @group legacy - * - * @expectedDeprecation Not explicitly passing an instance of "Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader" to "Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader" when it can optimize single id entity "%s" has been deprecated in 4.3 and will not apply any optimization in 5.0. - */ - public function testLoaderWithoutIdReaderCanBeOptimized() - { - $obj1 = new SingleIntIdEntity('1', 'one'); - $obj2 = new SingleIntIdEntity('2', 'two'); - - $metadata = $this->createMock(ClassMetadata::class); - $metadata->expects($this->once()) - ->method('getIdentifierFieldNames') - ->willReturn(['idField']) - ; - $metadata->expects($this->any()) - ->method('getIdentifierValues') - ->willReturnCallback(function ($obj) use ($obj1, $obj2) { - if ($obj === $obj1) { - return ['idField' => '1']; - } - if ($obj === $obj2) { - return ['idField' => '2']; - } - - return null; - }) - ; - - $this->om = $this->createMock(ObjectManager::class); - $this->om->expects($this->once()) - ->method('getClassMetadata') - ->with(SingleIntIdEntity::class) - ->willReturn($metadata) - ; - $this->om->expects($this->any()) - ->method('contains') - ->with($this->isInstanceOf(SingleIntIdEntity::class)) - ->willReturn(true) - ; - - $loader = new DoctrineChoiceLoader( - $this->om, - SingleIntIdEntity::class, - null, - $this->objectLoader - ); - - $choices = [$obj1, $obj2]; - - $this->repository->expects($this->never()) - ->method('findAll'); - - $this->objectLoader->expects($this->once()) - ->method('getEntitiesByIds') - ->with('idField', ['1']) - ->willReturn($choices); - - $this->assertSame([$obj1], $loader->loadChoicesForValues(['1'])); - } - - /** - * @group legacy - * - * @deprecationMessage Passing an instance of "Symfony\Bridge\Doctrine\Form\ChoiceList\IdReader" to "Symfony\Bridge\Doctrine\Form\ChoiceList\DoctrineChoiceLoader" with an entity class "stdClass" that has a composite id is deprecated since Symfony 4.3 and will throw an exception in 5.0. - */ public function testPassingIdReaderWithoutSingleIdEntity() { + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('The second argument `$idReader` of "Symfony\\Bridge\\Doctrine\\Form\\ChoiceList\\DoctrineChoiceLoader::__construct" must be null when the query cannot be optimized because of composite id fields.'); + $idReader = $this->createMock(IdReader::class); $idReader->expects($this->once()) ->method('isSingleId') ->willReturn(false) ; - $loader = new DoctrineChoiceLoader( - $this->om, - $this->class, - $idReader, - $this->objectLoader - ); - - $this->assertInstanceOf(DoctrineChoiceLoader::class, $loader); + new DoctrineChoiceLoader($this->om, $this->class, $idReader, $this->objectLoader); } } diff --git a/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/DoctrineExtractorTest.php b/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/DoctrineExtractorTest.php index dd5200117cfea..2a65ee9b0fc14 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/DoctrineExtractorTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/PropertyInfo/DoctrineExtractorTest.php @@ -24,7 +24,7 @@ */ class DoctrineExtractorTest extends TestCase { - private function createExtractor(bool $legacy = false) + private function createExtractor() { $config = Setup::createAnnotationMetadataConfiguration([__DIR__.\DIRECTORY_SEPARATOR.'Fixtures'], true); $entityManager = EntityManager::create(['driver' => 'pdo_sqlite'], $config); @@ -34,20 +34,10 @@ private function createExtractor(bool $legacy = false) $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('custom_foo', 'foo'); } - return new DoctrineExtractor($legacy ? $entityManager->getMetadataFactory() : $entityManager); + return new DoctrineExtractor($entityManager); } public function testGetProperties() - { - $this->doTestGetProperties(false); - } - - public function testLegacyGetProperties() - { - $this->doTestGetProperties(true); - } - - private function doTestGetProperties(bool $legacy) { $this->assertEquals( [ @@ -69,21 +59,11 @@ private function doTestGetProperties(bool $legacy) 'indexedBar', 'indexedFoo', ], - $this->createExtractor($legacy)->getProperties('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineDummy') + $this->createExtractor()->getProperties('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineDummy') ); } public function testTestGetPropertiesWithEmbedded() - { - $this->doTestGetPropertiesWithEmbedded(false); - } - - public function testLegacyTestGetPropertiesWithEmbedded() - { - $this->doTestGetPropertiesWithEmbedded(true); - } - - private function doTestGetPropertiesWithEmbedded(bool $legacy) { if (!class_exists('Doctrine\ORM\Mapping\Embedded')) { $this->markTestSkipped('@Embedded is not available in Doctrine ORM lower than 2.5.'); @@ -94,7 +74,7 @@ private function doTestGetPropertiesWithEmbedded(bool $legacy) 'id', 'embedded', ], - $this->createExtractor($legacy)->getProperties('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineWithEmbedded') + $this->createExtractor()->getProperties('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineWithEmbedded') ); } @@ -103,33 +83,10 @@ private function doTestGetPropertiesWithEmbedded(bool $legacy) */ public function testExtract($property, array $type = null) { - $this->doTestExtract(false, $property, $type); - } - - /** - * @dataProvider typesProvider - */ - public function testLegacyExtract($property, array $type = null) - { - $this->doTestExtract(true, $property, $type); - } - - private function doTestExtract(bool $legacy, $property, array $type = null) - { - $this->assertEquals($type, $this->createExtractor($legacy)->getTypes('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineDummy', $property, [])); + $this->assertEquals($type, $this->createExtractor()->getTypes('Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineDummy', $property, [])); } public function testExtractWithEmbedded() - { - $this->doTestExtractWithEmbedded(false); - } - - public function testLegacyExtractWithEmbedded() - { - $this->doTestExtractWithEmbedded(true); - } - - private function doTestExtractWithEmbedded(bool $legacy) { if (!class_exists('Doctrine\ORM\Mapping\Embedded')) { $this->markTestSkipped('@Embedded is not available in Doctrine ORM lower than 2.5.'); @@ -141,7 +98,7 @@ private function doTestExtractWithEmbedded(bool $legacy) 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineEmbeddable' )]; - $actualTypes = $this->createExtractor($legacy)->getTypes( + $actualTypes = $this->createExtractor()->getTypes( 'Symfony\Bridge\Doctrine\Tests\PropertyInfo\Fixtures\DoctrineWithEmbedded', 'embedded', [] @@ -197,32 +154,12 @@ public function typesProvider() public function testGetPropertiesCatchException() { - $this->doTestGetPropertiesCatchException(false); - } - - public function testLegacyGetPropertiesCatchException() - { - $this->doTestGetPropertiesCatchException(true); - } - - private function doTestGetPropertiesCatchException(bool $legacy) - { - $this->assertNull($this->createExtractor($legacy)->getProperties('Not\Exist')); + $this->assertNull($this->createExtractor()->getProperties('Not\Exist')); } public function testGetTypesCatchException() { - return $this->doTestGetTypesCatchException(false); - } - - public function testLegacyGetTypesCatchException() - { - return $this->doTestGetTypesCatchException(true); - } - - private function doTestGetTypesCatchException(bool $legacy) - { - $this->assertNull($this->createExtractor($legacy)->getTypes('Not\Exist', 'baz')); + $this->assertNull($this->createExtractor()->getTypes('Not\Exist', 'baz')); } public function testGeneratedValueNotWritable() diff --git a/src/Symfony/Bridge/Doctrine/Tests/Resources/validator/BaseUser.xml b/src/Symfony/Bridge/Doctrine/Tests/Resources/validator/BaseUser.xml index ddb8a13bc1fcc..40b7a138d437b 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Resources/validator/BaseUser.xml +++ b/src/Symfony/Bridge/Doctrine/Tests/Resources/validator/BaseUser.xml @@ -9,6 +9,12 @@ + + + + + + diff --git a/src/Symfony/Bridge/Doctrine/Tests/Validator/DoctrineLoaderTest.php b/src/Symfony/Bridge/Doctrine/Tests/Validator/DoctrineLoaderTest.php index 2c87b870a8e77..59163de651815 100644 --- a/src/Symfony/Bridge/Doctrine/Tests/Validator/DoctrineLoaderTest.php +++ b/src/Symfony/Bridge/Doctrine/Tests/Validator/DoctrineLoaderTest.php @@ -46,7 +46,6 @@ protected function setUp(): void public function testLoadClassMetadata() { $validator = Validation::createValidatorBuilder() - ->addMethodMapping('loadValidatorMetadata') ->enableAnnotationMapping() ->addLoader(new DoctrineLoader(DoctrineTestHelper::createTestEntityManager(), '{^Symfony\\\\Bridge\\\\Doctrine\\\\Tests\\\\Fixtures\\\\DoctrineLoader}')) ->getValidator() @@ -155,7 +154,6 @@ public function testFieldMappingsConfiguration() } $validator = Validation::createValidatorBuilder() - ->addMethodMapping('loadValidatorMetadata') ->enableAnnotationMapping() ->addXmlMappings([__DIR__.'/../Resources/validator/BaseUser.xml']) ->addLoader( diff --git a/src/Symfony/Bridge/Doctrine/Validator/DoctrineInitializer.php b/src/Symfony/Bridge/Doctrine/Validator/DoctrineInitializer.php index 010c051581e70..3b482565a8dfe 100644 --- a/src/Symfony/Bridge/Doctrine/Validator/DoctrineInitializer.php +++ b/src/Symfony/Bridge/Doctrine/Validator/DoctrineInitializer.php @@ -28,7 +28,7 @@ public function __construct(ManagerRegistry $registry) $this->registry = $registry; } - public function initialize($object) + public function initialize(object $object) { $manager = $this->registry->getManagerForClass(\get_class($object)); if (null !== $manager) { diff --git a/src/Symfony/Bridge/Doctrine/composer.json b/src/Symfony/Bridge/Doctrine/composer.json index 8c2d65c72801d..47e3003e37993 100644 --- a/src/Symfony/Bridge/Doctrine/composer.json +++ b/src/Symfony/Bridge/Doctrine/composer.json @@ -16,7 +16,7 @@ } ], "require": { - "php": "^7.1.3", + "php": "^7.2.5", "doctrine/event-manager": "~1.0", "doctrine/persistence": "~1.0", "symfony/polyfill-ctype": "~1.8", @@ -24,20 +24,20 @@ "symfony/service-contracts": "^1.1|^2" }, "require-dev": { - "symfony/stopwatch": "^3.4|^4.0|^5.0", - "symfony/config": "^4.2|^5.0", - "symfony/dependency-injection": "^3.4|^4.0|^5.0", - "symfony/form": "^4.4|^5.0", - "symfony/http-kernel": "^4.3.7", + "symfony/stopwatch": "^4.4|^5.0", + "symfony/config": "^4.4|^5.0", + "symfony/dependency-injection": "^4.4|^5.0", + "symfony/form": "^5.0", + "symfony/http-kernel": "^5.0", "symfony/messenger": "^4.4|^5.0", - "symfony/property-access": "^3.4|^4.0|^5.0", - "symfony/property-info": "^3.4|^4.0|^5.0", - "symfony/proxy-manager-bridge": "^3.4|^4.0|^5.0", - "symfony/security-core": "^4.4|^5.0", - "symfony/expression-language": "^3.4|^4.0|^5.0", - "symfony/validator": "^4.4|^5.0", - "symfony/var-dumper": "^3.4|^4.0|^5.0", - "symfony/translation": "^3.4|^4.0|^5.0", + "symfony/property-access": "^4.4|^5.0", + "symfony/property-info": "^5.0", + "symfony/proxy-manager-bridge": "^4.4|^5.0", + "symfony/security-core": "^5.0", + "symfony/expression-language": "^4.4|^5.0", + "symfony/validator": "^5.0", + "symfony/translation": "^4.4|^5.0", + "symfony/var-dumper": "^4.4|^5.0", "doctrine/annotations": "~1.7", "doctrine/cache": "~1.6", "doctrine/collections": "~1.0", @@ -47,13 +47,15 @@ "doctrine/reflection": "~1.0" }, "conflict": { - "phpunit/phpunit": "<4.8.35|<5.4.3,>=5.0", - "symfony/dependency-injection": "<3.4", - "symfony/form": "<4.4", - "symfony/http-kernel": "<4.3.7", - "symfony/messenger": "<4.3", - "symfony/security-core": "<4.4", - "symfony/validator": "<4.4" + "phpunit/phpunit": "<5.4.3", + "symfony/dependency-injection": "<4.4", + "symfony/form": "<5", + "symfony/http-kernel": "<5", + "symfony/messenger": "<4.4", + "symfony/property-info": "<5", + "symfony/security-bundle": "<5", + "symfony/security-core": "<5", + "symfony/validator": "<5" }, "suggest": { "symfony/form": "", @@ -72,7 +74,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.1-dev" } } } diff --git a/src/Symfony/Bridge/Monolog/CHANGELOG.md b/src/Symfony/Bridge/Monolog/CHANGELOG.md index e2439304faec0..7fdb07c47e5a5 100644 --- a/src/Symfony/Bridge/Monolog/CHANGELOG.md +++ b/src/Symfony/Bridge/Monolog/CHANGELOG.md @@ -1,6 +1,12 @@ CHANGELOG ========= +5.0.0 +----- + + * The methods `DebugProcessor::getLogs()`, `DebugProcessor::countErrors()`, `Logger::getLogs()` and `Logger::countErrors()` have a new `$request` argument. + * Added support for Monolog 2. + 4.4.0 ----- diff --git a/src/Symfony/Bridge/Monolog/Handler/ChromePhpHandler.php b/src/Symfony/Bridge/Monolog/Handler/ChromePhpHandler.php index abd7cc57b33d4..b1d9fcd51e242 100644 --- a/src/Symfony/Bridge/Monolog/Handler/ChromePhpHandler.php +++ b/src/Symfony/Bridge/Monolog/Handler/ChromePhpHandler.php @@ -13,14 +13,14 @@ use Monolog\Handler\ChromePHPHandler as BaseChromePhpHandler; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpKernel\Event\FilterResponseEvent; +use Symfony\Component\HttpKernel\Event\ResponseEvent; /** * ChromePhpHandler. * * @author Christophe Coevoet * - * @final since Symfony 4.3 + * @final */ class ChromePhpHandler extends BaseChromePhpHandler { @@ -34,7 +34,7 @@ class ChromePhpHandler extends BaseChromePhpHandler /** * Adds the headers to the response once it's created. */ - public function onKernelResponse(FilterResponseEvent $event) + public function onKernelResponse(ResponseEvent $event) { if (!$event->isMasterRequest()) { return; @@ -57,7 +57,7 @@ public function onKernelResponse(FilterResponseEvent $event) /** * {@inheritdoc} */ - protected function sendHeader($header, $content) + protected function sendHeader($header, $content): void { if (!$this->sendHeaders) { return; @@ -72,10 +72,8 @@ protected function sendHeader($header, $content) /** * Override default behavior since we check it in onKernelResponse. - * - * @return bool */ - protected function headersAccepted() + protected function headersAccepted(): bool { return true; } diff --git a/src/Symfony/Bridge/Monolog/Handler/ConsoleHandler.php b/src/Symfony/Bridge/Monolog/Handler/ConsoleHandler.php index 8dd4808fe8903..64b3d65fa5adf 100644 --- a/src/Symfony/Bridge/Monolog/Handler/ConsoleHandler.php +++ b/src/Symfony/Bridge/Monolog/Handler/ConsoleHandler.php @@ -74,20 +74,16 @@ public function __construct(OutputInterface $output = null, bool $bubble = true, /** * {@inheritdoc} - * - * @return bool */ - public function isHandling(array $record) + public function isHandling(array $record): bool { return $this->updateLevel() && parent::isHandling($record); } /** * {@inheritdoc} - * - * @return bool */ - public function handle(array $record) + public function handle(array $record): bool { // we have to update the logging level each time because the verbosity of the // console output might have changed in the meantime (it is not immutable) @@ -105,7 +101,7 @@ public function setOutput(OutputInterface $output) /** * Disables the output. */ - public function close() + public function close(): void { $this->output = null; @@ -147,10 +143,8 @@ public static function getSubscribedEvents() /** * {@inheritdoc} - * - * @return void */ - protected function write(array $record) + protected function write(array $record): void { // at this point we've determined for sure that we want to output the record, so use the output's own verbosity $this->output->write((string) $record['formatted'], false, $this->output->getVerbosity()); @@ -158,10 +152,8 @@ protected function write(array $record) /** * {@inheritdoc} - * - * @return FormatterInterface */ - protected function getDefaultFormatter() + protected function getDefaultFormatter(): FormatterInterface { if (!class_exists(CliDumper::class)) { return new LineFormatter(); diff --git a/src/Symfony/Bridge/Monolog/Handler/FingersCrossed/HttpCodeActivationStrategy.php b/src/Symfony/Bridge/Monolog/Handler/FingersCrossed/HttpCodeActivationStrategy.php index 062ca2103bb7e..cc0b19774c6c4 100644 --- a/src/Symfony/Bridge/Monolog/Handler/FingersCrossed/HttpCodeActivationStrategy.php +++ b/src/Symfony/Bridge/Monolog/Handler/FingersCrossed/HttpCodeActivationStrategy.php @@ -45,10 +45,7 @@ public function __construct(RequestStack $requestStack, array $exclusions, $acti $this->exclusions = $exclusions; } - /** - * @return bool - */ - public function isHandlerActivated(array $record) + public function isHandlerActivated(array $record): bool { $isActivated = parent::isHandlerActivated($record); diff --git a/src/Symfony/Bridge/Monolog/Handler/FingersCrossed/NotFoundActivationStrategy.php b/src/Symfony/Bridge/Monolog/Handler/FingersCrossed/NotFoundActivationStrategy.php index 08975d0c64b8d..4bea3cc8a8cdc 100644 --- a/src/Symfony/Bridge/Monolog/Handler/FingersCrossed/NotFoundActivationStrategy.php +++ b/src/Symfony/Bridge/Monolog/Handler/FingersCrossed/NotFoundActivationStrategy.php @@ -34,10 +34,7 @@ public function __construct(RequestStack $requestStack, array $excludedUrls, $ac $this->blacklist = '{('.implode('|', $excludedUrls).')}i'; } - /** - * @return bool - */ - public function isHandlerActivated(array $record) + public function isHandlerActivated(array $record): bool { $isActivated = parent::isHandlerActivated($record); diff --git a/src/Symfony/Bridge/Monolog/Handler/FirePHPHandler.php b/src/Symfony/Bridge/Monolog/Handler/FirePHPHandler.php index f006118223cba..0a9a6965db4a9 100644 --- a/src/Symfony/Bridge/Monolog/Handler/FirePHPHandler.php +++ b/src/Symfony/Bridge/Monolog/Handler/FirePHPHandler.php @@ -13,14 +13,14 @@ use Monolog\Handler\FirePHPHandler as BaseFirePHPHandler; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpKernel\Event\FilterResponseEvent; +use Symfony\Component\HttpKernel\Event\ResponseEvent; /** * FirePHPHandler. * * @author Jordi Boggiano * - * @final since Symfony 4.3 + * @final */ class FirePHPHandler extends BaseFirePHPHandler { @@ -34,7 +34,7 @@ class FirePHPHandler extends BaseFirePHPHandler /** * Adds the headers to the response once it's created. */ - public function onKernelResponse(FilterResponseEvent $event) + public function onKernelResponse(ResponseEvent $event) { if (!$event->isMasterRequest()) { return; @@ -59,7 +59,7 @@ public function onKernelResponse(FilterResponseEvent $event) /** * {@inheritdoc} */ - protected function sendHeader($header, $content) + protected function sendHeader($header, $content): void { if (!self::$sendHeaders) { return; @@ -74,10 +74,8 @@ protected function sendHeader($header, $content) /** * Override default behavior since we check the user agent in onKernelResponse. - * - * @return bool */ - protected function headersAccepted() + protected function headersAccepted(): bool { return true; } diff --git a/src/Symfony/Bridge/Monolog/Handler/NotifierHandler.php b/src/Symfony/Bridge/Monolog/Handler/NotifierHandler.php new file mode 100644 index 0000000000000..6152dece8f717 --- /dev/null +++ b/src/Symfony/Bridge/Monolog/Handler/NotifierHandler.php @@ -0,0 +1,79 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bridge\Monolog\Handler; + +use Monolog\Handler\AbstractHandler; +use Monolog\Logger; +use Symfony\Component\Notifier\Notification\Notification; +use Symfony\Component\Notifier\Notifier; +use Symfony\Component\Notifier\NotifierInterface; + +/** + * Uses Notifier as a log handler. + * + * @author Fabien Potencier + */ +class NotifierHandler extends AbstractHandler +{ + private $notifier; + + public function __construct(NotifierInterface $notifier, int $level = Logger::ERROR, bool $bubble = true) + { + $this->notifier = $notifier; + + parent::__construct($level < Logger::ERROR ? Logger::ERROR : $level, $bubble); + } + + public function handle(array $record): bool + { + if (!$this->isHandling($record)) { + return false; + } + + $this->notify([$record]); + + return !$this->bubble; + } + + public function handleBatch(array $records): void + { + if ($records = array_filter($records, [$this, 'isHandling'])) { + $this->notify($records); + } + } + + private function notify(array $records): void + { + $record = $this->getHighestRecord($records); + if (($record['context']['exception'] ?? null) instanceof \Throwable) { + $notification = Notification::fromThrowable($record['context']['exception']); + } else { + $notification = new Notification($record['message']); + } + + $notification->importanceFromLogLevelName(Logger::getLevelName($record['level'])); + + $this->notifier->send($notification, ...$this->notifier->getAdminRecipients()); + } + + private function getHighestRecord(array $records) + { + $highestRecord = null; + foreach ($records as $record) { + if (null === $highestRecord || $highestRecord['level'] < $record['level']) { + $highestRecord = $record; + } + } + + return $highestRecord; + } +} diff --git a/src/Symfony/Bridge/Monolog/Handler/ServerLogHandler.php b/src/Symfony/Bridge/Monolog/Handler/ServerLogHandler.php index 28582d31725a3..389e64d5aca8f 100644 --- a/src/Symfony/Bridge/Monolog/Handler/ServerLogHandler.php +++ b/src/Symfony/Bridge/Monolog/Handler/ServerLogHandler.php @@ -39,10 +39,8 @@ public function __construct(string $host, int $level = Logger::DEBUG, bool $bubb /** * {@inheritdoc} - * - * @return bool */ - public function handle(array $record) + public function handle(array $record): bool { if (!$this->isHandling($record)) { return false; diff --git a/src/Symfony/Bridge/Monolog/Handler/SwiftMailerHandler.php b/src/Symfony/Bridge/Monolog/Handler/SwiftMailerHandler.php index 93f2f72e6457a..f255f0a83ed16 100644 --- a/src/Symfony/Bridge/Monolog/Handler/SwiftMailerHandler.php +++ b/src/Symfony/Bridge/Monolog/Handler/SwiftMailerHandler.php @@ -13,14 +13,14 @@ use Monolog\Handler\SwiftMailerHandler as BaseSwiftMailerHandler; use Symfony\Component\Console\Event\ConsoleTerminateEvent; -use Symfony\Component\HttpKernel\Event\PostResponseEvent; +use Symfony\Component\HttpKernel\Event\TerminateEvent; /** * Extended SwiftMailerHandler that flushes mail queue if necessary. * * @author Philipp Kräutli * - * @final since Symfony 4.3 + * @final */ class SwiftMailerHandler extends BaseSwiftMailerHandler { @@ -36,7 +36,7 @@ public function setTransport(\Swift_Transport $transport) /** * After the kernel has been terminated we will always flush messages. */ - public function onKernelTerminate(PostResponseEvent $event) + public function onKernelTerminate(TerminateEvent $event) { $this->instantFlush = true; } @@ -52,7 +52,7 @@ public function onCliTerminate(ConsoleTerminateEvent $event) /** * {@inheritdoc} */ - protected function send($content, array $records) + protected function send($content, array $records): void { parent::send($content, $records); @@ -64,7 +64,7 @@ protected function send($content, array $records) /** * {@inheritdoc} */ - public function reset() + public function reset(): void { $this->flushMemorySpool(); } diff --git a/src/Symfony/Bridge/Monolog/Logger.php b/src/Symfony/Bridge/Monolog/Logger.php index e5d5987dd9328..4643f5b6d7598 100644 --- a/src/Symfony/Bridge/Monolog/Logger.php +++ b/src/Symfony/Bridge/Monolog/Logger.php @@ -24,17 +24,11 @@ class Logger extends BaseLogger implements DebugLoggerInterface, ResetInterface { /** * {@inheritdoc} - * - * @param Request|null $request */ - public function getLogs(/* Request $request = null */) + public function getLogs(Request $request = null) { - if (\func_num_args() < 1 && __CLASS__ !== \get_class($this) && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface) { - @trigger_error(sprintf('The "%s()" method will have a new "Request $request = null" argument in version 5.0, not defining it is deprecated since Symfony 4.2.', __METHOD__), E_USER_DEPRECATED); - } - if ($logger = $this->getDebugLogger()) { - return $logger->getLogs(...\func_get_args()); + return $logger->getLogs($request); } return []; @@ -42,17 +36,11 @@ public function getLogs(/* Request $request = null */) /** * {@inheritdoc} - * - * @param Request|null $request */ - public function countErrors(/* Request $request = null */) + public function countErrors(Request $request = null) { - if (\func_num_args() < 1 && __CLASS__ !== \get_class($this) && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface) { - @trigger_error(sprintf('The "%s()" method will have a new "Request $request = null" argument in version 5.0, not defining it is deprecated since Symfony 4.2.', __METHOD__), E_USER_DEPRECATED); - } - if ($logger = $this->getDebugLogger()) { - return $logger->countErrors(...\func_get_args()); + return $logger->countErrors($request); } return 0; @@ -71,7 +59,7 @@ public function clear() /** * {@inheritdoc} */ - public function reset() + public function reset(): void { $this->clear(); diff --git a/src/Symfony/Bridge/Monolog/Processor/DebugProcessor.php b/src/Symfony/Bridge/Monolog/Processor/DebugProcessor.php index f4e37ff44e739..a4594ca012bc2 100644 --- a/src/Symfony/Bridge/Monolog/Processor/DebugProcessor.php +++ b/src/Symfony/Bridge/Monolog/Processor/DebugProcessor.php @@ -58,16 +58,10 @@ public function __invoke(array $record) /** * {@inheritdoc} - * - * @param Request|null $request */ - public function getLogs(/* Request $request = null */) + public function getLogs(Request $request = null) { - if (\func_num_args() < 1 && __CLASS__ !== \get_class($this) && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface) { - @trigger_error(sprintf('The "%s()" method will have a new "Request $request = null" argument in version 5.0, not defining it is deprecated since Symfony 4.2.', __METHOD__), E_USER_DEPRECATED); - } - - if (1 <= \func_num_args() && null !== $request = func_get_arg(0)) { + if (null !== $request) { return $this->records[spl_object_hash($request)] ?? []; } @@ -80,16 +74,10 @@ public function getLogs(/* Request $request = null */) /** * {@inheritdoc} - * - * @param Request|null $request */ - public function countErrors(/* Request $request = null */) + public function countErrors(Request $request = null) { - if (\func_num_args() < 1 && __CLASS__ !== \get_class($this) && __CLASS__ !== (new \ReflectionMethod($this, __FUNCTION__))->getDeclaringClass()->getName() && !$this instanceof \PHPUnit\Framework\MockObject\MockObject && !$this instanceof \Prophecy\Prophecy\ProphecySubjectInterface) { - @trigger_error(sprintf('The "%s()" method will have a new "Request $request = null" argument in version 5.0, not defining it is deprecated since Symfony 4.2.', __METHOD__), E_USER_DEPRECATED); - } - - if (1 <= \func_num_args() && null !== $request = func_get_arg(0)) { + if (null !== $request) { return $this->errorCount[spl_object_hash($request)] ?? 0; } diff --git a/src/Symfony/Bridge/Monolog/Processor/RouteProcessor.php b/src/Symfony/Bridge/Monolog/Processor/RouteProcessor.php index 09507b55e7fb2..23b95d9b8512c 100644 --- a/src/Symfony/Bridge/Monolog/Processor/RouteProcessor.php +++ b/src/Symfony/Bridge/Monolog/Processor/RouteProcessor.php @@ -13,7 +13,7 @@ use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\FinishRequestEvent; -use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Contracts\Service\ResetInterface; @@ -22,7 +22,7 @@ * * @author Piotr Stankowski * - * @final since Symfony 4.4 + * @final */ class RouteProcessor implements EventSubscriberInterface, ResetInterface { @@ -35,7 +35,7 @@ public function __construct(bool $includeParams = true) $this->reset(); } - public function __invoke(array $records) + public function __invoke(array $records): array { if ($this->routeData && !isset($records['extra']['requests'])) { $records['extra']['requests'] = array_values($this->routeData); @@ -49,7 +49,7 @@ public function reset() $this->routeData = []; } - public function addRouteData(GetResponseEvent $event) + public function addRouteData(RequestEvent $event) { if ($event->isMasterRequest()) { $this->reset(); @@ -78,7 +78,7 @@ public function removeRouteData(FinishRequestEvent $event) unset($this->routeData[$requestId]); } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ KernelEvents::REQUEST => ['addRouteData', 1], diff --git a/src/Symfony/Bridge/Monolog/Processor/TokenProcessor.php b/src/Symfony/Bridge/Monolog/Processor/TokenProcessor.php index 7613d01361962..78d8dd3249c6d 100644 --- a/src/Symfony/Bridge/Monolog/Processor/TokenProcessor.php +++ b/src/Symfony/Bridge/Monolog/Processor/TokenProcessor.php @@ -31,11 +31,7 @@ public function __invoke(array $records) { $records['extra']['token'] = null; if (null !== $token = $this->tokenStorage->getToken()) { - if (method_exists($token, 'getRoleNames')) { - $roles = $token->getRoleNames(); - } else { - $roles = array_map(function ($role) { return $role->getRole(); }, $token->getRoles(false)); - } + $roles = $token->getRoleNames(); $records['extra']['token'] = [ 'username' => $token->getUsername(), diff --git a/src/Symfony/Bridge/Monolog/Processor/WebProcessor.php b/src/Symfony/Bridge/Monolog/Processor/WebProcessor.php index 71bf71a816327..98ec10ca6dcb4 100644 --- a/src/Symfony/Bridge/Monolog/Processor/WebProcessor.php +++ b/src/Symfony/Bridge/Monolog/Processor/WebProcessor.php @@ -13,7 +13,7 @@ use Monolog\Processor\WebProcessor as BaseWebProcessor; use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; /** @@ -21,7 +21,7 @@ * * @author Jordi Boggiano * - * @final since Symfony 4.3 + * @final */ class WebProcessor extends BaseWebProcessor implements EventSubscriberInterface { @@ -31,7 +31,7 @@ public function __construct(array $extraFields = null) parent::__construct([], $extraFields); } - public function onKernelRequest(GetResponseEvent $event) + public function onKernelRequest(RequestEvent $event) { if ($event->isMasterRequest()) { $this->serverData = $event->getRequest()->server->all(); @@ -39,7 +39,7 @@ public function onKernelRequest(GetResponseEvent $event) } } - public static function getSubscribedEvents() + public static function getSubscribedEvents(): array { return [ KernelEvents::REQUEST => ['onKernelRequest', 4096], diff --git a/src/Symfony/Bridge/Monolog/Tests/ClassThatInheritLogger.php b/src/Symfony/Bridge/Monolog/Tests/ClassThatInheritLogger.php index 31c62e3e75591..e258c7942a20a 100644 --- a/src/Symfony/Bridge/Monolog/Tests/ClassThatInheritLogger.php +++ b/src/Symfony/Bridge/Monolog/Tests/ClassThatInheritLogger.php @@ -12,16 +12,17 @@ namespace Symfony\Bridge\Monolog\Tests; use Symfony\Bridge\Monolog\Logger; +use Symfony\Component\HttpFoundation\Request; class ClassThatInheritLogger extends Logger { - public function getLogs(): array + public function getLogs(Request $request = null): array { - return parent::getLogs(); + return parent::getLogs($request); } - public function countErrors(): int + public function countErrors(Request $request = null): int { - return parent::countErrors(); + return parent::countErrors($request); } } diff --git a/src/Symfony/Bridge/Monolog/Tests/LoggerTest.php b/src/Symfony/Bridge/Monolog/Tests/LoggerTest.php index 2b2c7a3763a72..f170c526b8f74 100644 --- a/src/Symfony/Bridge/Monolog/Tests/LoggerTest.php +++ b/src/Symfony/Bridge/Monolog/Tests/LoggerTest.php @@ -125,15 +125,15 @@ public function testReset() } } - /** - * @group legacy - * @expectedDeprecation The "Symfony\Bridge\Monolog\Logger::getLogs()" method will have a new "Request $request = null" argument in version 5.0, not defining it is deprecated since Symfony 4.2. - * @expectedDeprecation The "Symfony\Bridge\Monolog\Logger::countErrors()" method will have a new "Request $request = null" argument in version 5.0, not defining it is deprecated since Symfony 4.2. - */ - public function testInheritedClassWithoutArgument() + public function testInheritedClassCallGetLogsWithoutArgument() { $loggerChild = new ClassThatInheritLogger('test'); - $loggerChild->getLogs(); - $loggerChild->countErrors(); + $this->assertSame([], $loggerChild->getLogs()); + } + + public function testInheritedClassCallCountErrorsWithoutArgument() + { + $loggerChild = new ClassThatInheritLogger('test'); + $this->assertEquals(0, $loggerChild->countErrors()); } } diff --git a/src/Symfony/Bridge/Monolog/Tests/Processor/ClassThatInheritDebugProcessor.php b/src/Symfony/Bridge/Monolog/Tests/Processor/ClassThatInheritDebugProcessor.php index 1f15bd9f764b2..bc87c724c9d31 100644 --- a/src/Symfony/Bridge/Monolog/Tests/Processor/ClassThatInheritDebugProcessor.php +++ b/src/Symfony/Bridge/Monolog/Tests/Processor/ClassThatInheritDebugProcessor.php @@ -12,16 +12,17 @@ namespace Symfony\Bridge\Monolog\Tests\Processor; use Symfony\Bridge\Monolog\Processor\DebugProcessor; +use Symfony\Component\HttpFoundation\Request; class ClassThatInheritDebugProcessor extends DebugProcessor { - public function getLogs(): array + public function getLogs(Request $request = null): array { - return parent::getLogs(); + return parent::getLogs($request); } - public function countErrors(): int + public function countErrors(Request $request = null): int { - return parent::countErrors(); + return parent::countErrors($request); } } diff --git a/src/Symfony/Bridge/Monolog/Tests/Processor/DebugProcessorTest.php b/src/Symfony/Bridge/Monolog/Tests/Processor/DebugProcessorTest.php index 37456b801dcdd..7a1e6706878be 100644 --- a/src/Symfony/Bridge/Monolog/Tests/Processor/DebugProcessorTest.php +++ b/src/Symfony/Bridge/Monolog/Tests/Processor/DebugProcessorTest.php @@ -63,16 +63,16 @@ public function testWithRequestStack() $this->assertSame(0, $processor->countErrors(new Request())); } - /** - * @group legacy - * @expectedDeprecation The "Symfony\Bridge\Monolog\Processor\DebugProcessor::getLogs()" method will have a new "Request $request = null" argument in version 5.0, not defining it is deprecated since Symfony 4.2. - * @expectedDeprecation The "Symfony\Bridge\Monolog\Processor\DebugProcessor::countErrors()" method will have a new "Request $request = null" argument in version 5.0, not defining it is deprecated since Symfony 4.2. - */ - public function testInheritedClassWithoutArgument() + public function testInheritedClassCallGetLogsWithoutArgument() { $debugProcessorChild = new ClassThatInheritDebugProcessor(); - $debugProcessorChild->getLogs(); - $debugProcessorChild->countErrors(); + $this->assertSame([], $debugProcessorChild->getLogs()); + } + + public function testInheritedClassCallCountErrorsWithoutArgument() + { + $debugProcessorChild = new ClassThatInheritDebugProcessor(); + $this->assertEquals(0, $debugProcessorChild->countErrors()); } private function getRecord($level = Logger::WARNING, $message = 'test') diff --git a/src/Symfony/Bridge/Monolog/composer.json b/src/Symfony/Bridge/Monolog/composer.json index 0325ed5447a8d..6a0777aac13b2 100644 --- a/src/Symfony/Bridge/Monolog/composer.json +++ b/src/Symfony/Bridge/Monolog/composer.json @@ -16,20 +16,20 @@ } ], "require": { - "php": "^7.1.3", - "monolog/monolog": "^1.25.1", + "php": "^7.2.5", + "monolog/monolog": "^1.25.1|^2", "symfony/service-contracts": "^1.1|^2", - "symfony/http-kernel": "^4.3" + "symfony/http-kernel": "^4.4|^5.0" }, "require-dev": { - "symfony/console": "^3.4|^4.0|^5.0", + "symfony/console": "^4.4|^5.0", "symfony/http-client": "^4.4|^5.0", - "symfony/security-core": "^3.4|^4.0|^5.0", - "symfony/var-dumper": "^3.4|^4.0|^5.0" + "symfony/security-core": "^4.4|^5.0", + "symfony/var-dumper": "^4.4|^5.0" }, "conflict": { - "symfony/console": "<3.4", - "symfony/http-foundation": "<3.4" + "symfony/console": "<4.4", + "symfony/http-foundation": "<4.4" }, "suggest": { "symfony/http-kernel": "For using the debugging handlers together with the response life cycle of the HTTP kernel.", @@ -45,7 +45,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.1-dev" } } } diff --git a/src/Symfony/Bridge/PhpUnit/CHANGELOG.md b/src/Symfony/Bridge/PhpUnit/CHANGELOG.md index b85364ad7dd7f..17c3f201bff7d 100644 --- a/src/Symfony/Bridge/PhpUnit/CHANGELOG.md +++ b/src/Symfony/Bridge/PhpUnit/CHANGELOG.md @@ -1,6 +1,11 @@ CHANGELOG ========= +5.0.0 +----- + + * removed `weak_vendor` mode, use `max[self]=0` instead + 4.4.0 ----- diff --git a/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php b/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php index 1519fb2bbf184..0b14604d5a175 100644 --- a/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php +++ b/src/Symfony/Bridge/PhpUnit/DeprecationErrorHandler.php @@ -24,11 +24,6 @@ */ class DeprecationErrorHandler { - /** - * @deprecated since Symfony 4.3, use max[self]=0 instead - */ - const MODE_WEAK_VENDORS = 'weak_vendors'; - const MODE_DISABLED = 'disabled'; const MODE_WEAK = 'max[total]=999999&verbose=0'; const MODE_STRICT = 'max[total]=0'; @@ -240,13 +235,6 @@ private function getConfiguration() if ('weak' === $mode) { return $this->configuration = Configuration::inWeakMode(); } - if (self::MODE_WEAK_VENDORS === $mode) { - ++$this->deprecations['remaining directCount']; - $msg = sprintf('Setting SYMFONY_DEPRECATIONS_HELPER to "%s" is deprecated in favor of "max[self]=0"', $mode); - $ref = &$this->deprecations['remaining direct'][$msg]['count']; - ++$ref; - $mode = 'max[self]=0'; - } if (isset($mode[0]) && '/' === $mode[0]) { return $this->configuration = Configuration::fromRegex($mode); } diff --git a/src/Symfony/Bridge/PhpUnit/composer.json b/src/Symfony/Bridge/PhpUnit/composer.json index 6d06cb3fefc51..e5395bccd70fb 100644 --- a/src/Symfony/Bridge/PhpUnit/composer.json +++ b/src/Symfony/Bridge/PhpUnit/composer.json @@ -24,7 +24,7 @@ "symfony/error-handler": "For tracking deprecated interfaces usages at runtime with DebugClassLoader" }, "conflict": { - "phpunit/phpunit": "<4.8.35|<5.4.3,>=5.0" + "phpunit/phpunit": "<5.4.3" }, "autoload": { "files": [ "bootstrap.php" ], @@ -39,7 +39,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.1-dev" }, "thanks": { "name": "phpunit/phpunit", diff --git a/src/Symfony/Bridge/ProxyManager/LazyProxy/Instantiator/RuntimeInstantiator.php b/src/Symfony/Bridge/ProxyManager/LazyProxy/Instantiator/RuntimeInstantiator.php index 7b6ce56b0fbe9..eee54e5ca25c8 100644 --- a/src/Symfony/Bridge/ProxyManager/LazyProxy/Instantiator/RuntimeInstantiator.php +++ b/src/Symfony/Bridge/ProxyManager/LazyProxy/Instantiator/RuntimeInstantiator.php @@ -38,7 +38,7 @@ public function __construct() /** * {@inheritdoc} */ - public function instantiateProxy(ContainerInterface $container, Definition $definition, $id, $realInstantiator) + public function instantiateProxy(ContainerInterface $container, Definition $definition, string $id, callable $realInstantiator) { return $this->factory->createProxy( $this->factory->getGenerator()->getProxifiedClass($definition), diff --git a/src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/ProxyDumper.php b/src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/ProxyDumper.php index 0854f7f18360a..dcf7b622cebe1 100644 --- a/src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/ProxyDumper.php +++ b/src/Symfony/Bridge/ProxyManager/LazyProxy/PhpDumper/ProxyDumper.php @@ -48,7 +48,7 @@ public function isProxyCandidate(Definition $definition): bool /** * {@inheritdoc} */ - public function getProxyFactoryCode(Definition $definition, $id, $factoryCode = null): string + public function getProxyFactoryCode(Definition $definition, string $id, string $factoryCode): string { $instantiation = 'return'; @@ -56,10 +56,6 @@ public function getProxyFactoryCode(Definition $definition, $id, $factoryCode = $instantiation .= sprintf(' $this->%s[%s] =', $definition->isPublic() && !$definition->isPrivate() ? 'services' : 'privates', var_export($id, true)); } - if (null === $factoryCode) { - throw new \InvalidArgumentException(sprintf('Missing factory code to construct the service "%s".', $id)); - } - $proxyClass = $this->getProxyClassName($definition); return <<expectException('InvalidArgumentException'); - $this->expectExceptionMessage('Missing factory code to construct the service "foo".'); - $definition = new Definition(__CLASS__); - $definition->setLazy(true); - $this->dumper->getProxyFactoryCode($definition, 'foo'); - } - public function testGetProxyFactoryCodeForInterface() { $class = DummyClass::class; diff --git a/src/Symfony/Bridge/ProxyManager/composer.json b/src/Symfony/Bridge/ProxyManager/composer.json index c7038a9c19d48..99effe166c816 100644 --- a/src/Symfony/Bridge/ProxyManager/composer.json +++ b/src/Symfony/Bridge/ProxyManager/composer.json @@ -16,12 +16,12 @@ } ], "require": { - "php": "^7.1.3", - "symfony/dependency-injection": "^4.0|^5.0", + "php": "^7.2.5", + "symfony/dependency-injection": "^5.0", "ocramius/proxy-manager": "~2.1" }, "require-dev": { - "symfony/config": "^3.4|^4.0|^5.0" + "symfony/config": "^4.4|^5.0" }, "conflict": { "zendframework/zend-eventmanager": "2.6.0" @@ -35,7 +35,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.1-dev" } } } diff --git a/src/Symfony/Bridge/Twig/AppVariable.php b/src/Symfony/Bridge/Twig/AppVariable.php index 4a22265908b42..f5a6494ed29bc 100644 --- a/src/Symfony/Bridge/Twig/AppVariable.php +++ b/src/Symfony/Bridge/Twig/AppVariable.php @@ -39,14 +39,14 @@ public function setRequestStack(RequestStack $requestStack) $this->requestStack = $requestStack; } - public function setEnvironment($environment) + public function setEnvironment(string $environment) { $this->environment = $environment; } - public function setDebug($debug) + public function setDebug(bool $debug) { - $this->debug = (bool) $debug; + $this->debug = $debug; } /** diff --git a/src/Symfony/Bridge/Twig/CHANGELOG.md b/src/Symfony/Bridge/Twig/CHANGELOG.md index 71a30ae880d78..c70801a89014c 100644 --- a/src/Symfony/Bridge/Twig/CHANGELOG.md +++ b/src/Symfony/Bridge/Twig/CHANGELOG.md @@ -1,6 +1,14 @@ CHANGELOG ========= +5.0.0 +----- + + * removed `TwigEngine` class, use `\Twig\Environment` instead. + * removed `transChoice` filter and token + * `HttpFoundationExtension` requires a `UrlHelper` on instantiation + * removed support for implicit STDIN usage in the `lint:twig` command, use `lint:twig -` (append a dash) instead to make it explicit. + 4.4.0 ----- diff --git a/src/Symfony/Bridge/Twig/Command/DebugCommand.php b/src/Symfony/Bridge/Twig/Command/DebugCommand.php index edefbd8bcb452..2f365c216b423 100644 --- a/src/Symfony/Bridge/Twig/Command/DebugCommand.php +++ b/src/Symfony/Bridge/Twig/Command/DebugCommand.php @@ -38,15 +38,10 @@ class DebugCommand extends Command private $projectDir; private $bundlesMetadata; private $twigDefaultPath; - private $rootDir; private $filesystemLoaders; private $fileLinkFormatter; - /** - * @param FileLinkFormatter|null $fileLinkFormatter - * @param string|null $rootDir - */ - public function __construct(Environment $twig, string $projectDir = null, array $bundlesMetadata = [], string $twigDefaultPath = null, $fileLinkFormatter = null, $rootDir = null) + public function __construct(Environment $twig, string $projectDir = null, array $bundlesMetadata = [], string $twigDefaultPath = null, FileLinkFormatter $fileLinkFormatter = null) { parent::__construct(); @@ -54,16 +49,7 @@ public function __construct(Environment $twig, string $projectDir = null, array $this->projectDir = $projectDir; $this->bundlesMetadata = $bundlesMetadata; $this->twigDefaultPath = $twigDefaultPath; - - if (\is_string($fileLinkFormatter) || $rootDir instanceof FileLinkFormatter) { - @trigger_error(sprintf('Passing a string as "$fileLinkFormatter" 5th argument or an instance of FileLinkFormatter as "$rootDir" 6th argument of the "%s()" method is deprecated since Symfony 4.4, swap the variables position.', __METHOD__), E_USER_DEPRECATED); - - $this->rootDir = $fileLinkFormatter; - $this->fileLinkFormatter = $rootDir; - } else { - $this->fileLinkFormatter = $fileLinkFormatter; - $this->rootDir = $rootDir; - } + $this->fileLinkFormatter = $fileLinkFormatter; } protected function configure() @@ -405,22 +391,6 @@ private function findWrongBundleOverrides(): array $alternatives = []; $bundleNames = []; - if ($this->rootDir && $this->projectDir) { - $folders = glob($this->rootDir.'/Resources/*/views', GLOB_ONLYDIR); - $relativePath = ltrim(substr($this->rootDir.\DIRECTORY_SEPARATOR.'Resources/', \strlen($this->projectDir)), \DIRECTORY_SEPARATOR); - $bundleNames = array_reduce($folders, function ($carry, $absolutePath) use ($relativePath) { - if (0 === strpos($absolutePath, $this->projectDir)) { - $name = basename(\dirname($absolutePath)); - $path = ltrim($relativePath.$name, \DIRECTORY_SEPARATOR); - $carry[$name] = $path; - - @trigger_error(sprintf('Loading Twig templates from the "%s" directory is deprecated since Symfony 4.2, use "%s" instead.', $absolutePath, $this->twigDefaultPath.'/bundles/'.$name), E_USER_DEPRECATED); - } - - return $carry; - }, $bundleNames); - } - if ($this->twigDefaultPath && $this->projectDir) { $folders = glob($this->twigDefaultPath.'/bundles/*', GLOB_ONLYDIR); $relativePath = ltrim(substr($this->twigDefaultPath.'/bundles/', \strlen($this->projectDir)), \DIRECTORY_SEPARATOR); diff --git a/src/Symfony/Bridge/Twig/Command/LintCommand.php b/src/Symfony/Bridge/Twig/Command/LintCommand.php index 20db8c5de12fd..a41e3ea9a5100 100644 --- a/src/Symfony/Bridge/Twig/Command/LintCommand.php +++ b/src/Symfony/Bridge/Twig/Command/LintCommand.php @@ -85,13 +85,6 @@ protected function execute(InputInterface $input, OutputInterface $output) } if (!$filenames) { - // @deprecated to be removed in 5.0 - if (0 === ftell(STDIN)) { - @trigger_error('Piping content from STDIN to the "lint:twig" command without passing the dash symbol "-" as argument is deprecated since Symfony 4.4.', E_USER_DEPRECATED); - - return $this->display($input, $output, $io, [$this->validate(file_get_contents('php://stdin'), uniqid('sf_', true))]); - } - $loader = $this->twig->getLoader(); if ($loader instanceof FilesystemLoader) { $paths = []; @@ -144,7 +137,7 @@ private function getFilesInfo(array $filenames): array return $filesInfo; } - protected function findFiles($filename) + protected function findFiles(string $filename) { if (is_file($filename)) { return [$filename]; diff --git a/src/Symfony/Bridge/Twig/DataCollector/TwigDataCollector.php b/src/Symfony/Bridge/Twig/DataCollector/TwigDataCollector.php index fd6bc2d1e2663..be432838ff45a 100644 --- a/src/Symfony/Bridge/Twig/DataCollector/TwigDataCollector.php +++ b/src/Symfony/Bridge/Twig/DataCollector/TwigDataCollector.php @@ -26,7 +26,7 @@ * * @author Fabien Potencier * - * @final since Symfony 4.4 + * @final */ class TwigDataCollector extends DataCollector implements LateDataCollectorInterface { @@ -42,10 +42,8 @@ public function __construct(Profile $profile, Environment $twig = null) /** * {@inheritdoc} - * - * @param \Throwable|null $exception */ - public function collect(Request $request, Response $response/*, \Throwable $exception = null*/) + public function collect(Request $request, Response $response, \Throwable $exception = null) { } diff --git a/src/Symfony/Bridge/Twig/ErrorRenderer/TwigErrorRenderer.php b/src/Symfony/Bridge/Twig/ErrorRenderer/TwigErrorRenderer.php index 93fe767062713..bc5f24ba7a804 100644 --- a/src/Symfony/Bridge/Twig/ErrorRenderer/TwigErrorRenderer.php +++ b/src/Symfony/Bridge/Twig/ErrorRenderer/TwigErrorRenderer.php @@ -16,8 +16,6 @@ use Symfony\Component\ErrorHandler\Exception\FlattenException; use Symfony\Component\HttpFoundation\RequestStack; use Twig\Environment; -use Twig\Error\LoaderError; -use Twig\Loader\ExistsLoaderInterface; /** * Provides the ability to render custom Twig-based HTML error pages @@ -58,7 +56,6 @@ public function render(\Throwable $exception): FlattenException } return $exception->setAsString($this->twig->render($template, [ - 'legacy' => false, // to be removed in 5.0 'exception' => $exception, 'status_code' => $exception->getStatusCode(), 'status_text' => $exception->getStatusText(), @@ -79,39 +76,15 @@ public static function isDebug(RequestStack $requestStack, bool $debug): \Closur private function findTemplate(int $statusCode): ?string { $template = sprintf('@Twig/Exception/error%s.html.twig', $statusCode); - if ($this->templateExists($template)) { + if ($this->twig->getLoader()->exists($template)) { return $template; } $template = '@Twig/Exception/error.html.twig'; - if ($this->templateExists($template)) { + if ($this->twig->getLoader()->exists($template)) { return $template; } return null; } - - /** - * To be removed in 5.0. - * - * Use instead: - * - * $this->twig->getLoader()->exists($template) - */ - private function templateExists(string $template): bool - { - $loader = $this->twig->getLoader(); - if ($loader instanceof ExistsLoaderInterface || method_exists($loader, 'exists')) { - return $loader->exists($template); - } - - try { - $loader->getSourceContext($template); - - return true; - } catch (LoaderError $e) { - } - - return false; - } } diff --git a/src/Symfony/Bridge/Twig/Extension/AssetExtension.php b/src/Symfony/Bridge/Twig/Extension/AssetExtension.php index 62e7b91cb2db6..694821f7bf6b8 100644 --- a/src/Symfony/Bridge/Twig/Extension/AssetExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/AssetExtension.php @@ -19,10 +19,8 @@ * Twig extension for the Symfony Asset component. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class AssetExtension extends AbstractExtension +final class AssetExtension extends AbstractExtension { private $packages; @@ -33,10 +31,8 @@ public function __construct(Packages $packages) /** * {@inheritdoc} - * - * @return TwigFunction[] */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('asset', [$this, 'getAssetUrl']), @@ -49,37 +45,17 @@ public function getFunctions() * * If the package used to generate the path is an instance of * UrlPackage, you will always get a URL and not a path. - * - * @param string $path A public path - * @param string $packageName The name of the asset package to use - * - * @return string The public path of the asset */ - public function getAssetUrl($path, $packageName = null) + public function getAssetUrl(string $path, string $packageName = null): string { return $this->packages->getUrl($path, $packageName); } /** * Returns the version of an asset. - * - * @param string $path A public path - * @param string $packageName The name of the asset package to use - * - * @return string The asset version */ - public function getAssetVersion($path, $packageName = null) + public function getAssetVersion(string $path, string $packageName = null): string { return $this->packages->getVersion($path, $packageName); } - - /** - * Returns the name of the extension. - * - * @return string The extension name - */ - public function getName() - { - return 'asset'; - } } diff --git a/src/Symfony/Bridge/Twig/Extension/CodeExtension.php b/src/Symfony/Bridge/Twig/Extension/CodeExtension.php index d91e1c1676000..f35725af0da9e 100644 --- a/src/Symfony/Bridge/Twig/Extension/CodeExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/CodeExtension.php @@ -19,10 +19,8 @@ * Twig extension relate to PHP code and used by the profiler and the default exception templates. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class CodeExtension extends AbstractExtension +final class CodeExtension extends AbstractExtension { private $fileLinkFormat; private $charset; @@ -30,8 +28,6 @@ class CodeExtension extends AbstractExtension /** * @param string|FileLinkFormatter $fileLinkFormat The format for links to source files - * @param string $projectDir The project directory - * @param string $charset The charset */ public function __construct($fileLinkFormat, string $projectDir, string $charset) { @@ -42,10 +38,8 @@ public function __construct($fileLinkFormat, string $projectDir, string $charset /** * {@inheritdoc} - * - * @return TwigFilter[] */ - public function getFilters() + public function getFilters(): array { return [ new TwigFilter('abbr_class', [$this, 'abbrClass'], ['is_safe' => ['html']]), @@ -61,7 +55,7 @@ public function getFilters() ]; } - public function abbrClass($class) + public function abbrClass(string $class): string { $parts = explode('\\', $class); $short = array_pop($parts); @@ -69,7 +63,7 @@ public function abbrClass($class) return sprintf('%s', $class, $short); } - public function abbrMethod($method) + public function abbrMethod(string $method): string { if (false !== strpos($method, '::')) { list($class, $method) = explode('::', $method, 2); @@ -85,12 +79,8 @@ public function abbrMethod($method) /** * Formats an array as a string. - * - * @param array $args The argument array - * - * @return string */ - public function formatArgs($args) + public function formatArgs(array $args): string { $result = []; foreach ($args as $key => $item) { @@ -118,26 +108,16 @@ public function formatArgs($args) /** * Formats an array as a string. - * - * @param array $args The argument array - * - * @return string */ - public function formatArgsAsText($args) + public function formatArgsAsText(array $args): string { return strip_tags($this->formatArgs($args)); } /** * Returns an excerpt of a code file around the given line number. - * - * @param string $file A file path - * @param int $line The selected line number - * @param int $srcContext The number of displayed lines around or -1 for the whole file - * - * @return string An HTML string */ - public function fileExcerpt($file, $line, $srcContext = 3) + public function fileExcerpt(string $file, int $line, int $srcContext = 3): ?string { if (is_file($file) && is_readable($file)) { // highlight_file could throw warnings @@ -168,14 +148,8 @@ public function fileExcerpt($file, $line, $srcContext = 3) /** * Formats a file path. - * - * @param string $file An absolute file path - * @param int $line The line number - * @param string $text Use this text for the link rather than the file path - * - * @return string */ - public function formatFile($file, $line, $text = null) + public function formatFile(string $file, int $line, string $text = null): string { $file = trim($file); @@ -201,12 +175,9 @@ public function formatFile($file, $line, $text = null) /** * Returns the link for a given file/line pair. * - * @param string $file An absolute file path - * @param int $line The line number - * * @return string|false A link or false */ - public function getFileLink($file, $line) + public function getFileLink(string $file, int $line) { if ($fmt = $this->fileLinkFormat) { return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line); @@ -226,7 +197,7 @@ public function getFileRelative(string $file): ?string return null; } - public function formatFileFromText($text) + public function formatFileFromText(string $text): string { return preg_replace_callback('/in ("|")?(.+?)\1(?: +(?:on|at))? +line (\d+)/s', function ($match) { return 'in '.$this->formatFile($match[2], $match[3]); @@ -254,15 +225,7 @@ public function formatLogMessage(string $message, array $context): string return htmlspecialchars($message, ENT_COMPAT | ENT_SUBSTITUTE, $this->charset); } - /** - * {@inheritdoc} - */ - public function getName() - { - return 'code'; - } - - protected static function fixCodeMarkup($line) + protected static function fixCodeMarkup(string $line): string { // ending tag from previous line $opening = strpos($line, ' * @author Titouan Galopin - * - * @final since Symfony 4.4 */ -class CsrfExtension extends AbstractExtension +final class CsrfExtension extends AbstractExtension { /** * {@inheritdoc} diff --git a/src/Symfony/Bridge/Twig/Extension/CsrfRuntime.php b/src/Symfony/Bridge/Twig/Extension/CsrfRuntime.php index ea857c7ed583b..c3d5da6470c25 100644 --- a/src/Symfony/Bridge/Twig/Extension/CsrfRuntime.php +++ b/src/Symfony/Bridge/Twig/Extension/CsrfRuntime.php @@ -16,10 +16,8 @@ /** * @author Christian Flothmann * @author Titouan Galopin - * - * @final since Symfony 4.4 */ -class CsrfRuntime +final class CsrfRuntime { private $csrfTokenManager; diff --git a/src/Symfony/Bridge/Twig/Extension/DumpExtension.php b/src/Symfony/Bridge/Twig/Extension/DumpExtension.php index 1ba9863a9756f..2187ed99bfb2a 100644 --- a/src/Symfony/Bridge/Twig/Extension/DumpExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/DumpExtension.php @@ -17,17 +17,14 @@ use Twig\Environment; use Twig\Extension\AbstractExtension; use Twig\Template; -use Twig\TokenParser\TokenParserInterface; use Twig\TwigFunction; /** * Provides integration of the dump() function with Twig. * * @author Nicolas Grekas - * - * @final since Symfony 4.4 */ -class DumpExtension extends AbstractExtension +final class DumpExtension extends AbstractExtension { private $cloner; private $dumper; @@ -39,9 +36,9 @@ public function __construct(ClonerInterface $cloner, HtmlDumper $dumper = null) } /** - * @return TwigFunction[] + * {@inheritdoc} */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('dump', [$this, 'dump'], ['is_safe' => ['html'], 'needs_context' => true, 'needs_environment' => true]), @@ -49,19 +46,14 @@ public function getFunctions() } /** - * @return TokenParserInterface[] + * {@inheritdoc} */ - public function getTokenParsers() + public function getTokenParsers(): array { return [new DumpTokenParser()]; } - public function getName() - { - return 'dump'; - } - - public function dump(Environment $env, $context) + public function dump(Environment $env, array $context): ?string { if (!$env->isDebug()) { return null; diff --git a/src/Symfony/Bridge/Twig/Extension/ExpressionExtension.php b/src/Symfony/Bridge/Twig/Extension/ExpressionExtension.php index af7be97c4f9bd..8d2a35c99f682 100644 --- a/src/Symfony/Bridge/Twig/Extension/ExpressionExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/ExpressionExtension.php @@ -19,35 +19,21 @@ * ExpressionExtension gives a way to create Expressions from a template. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class ExpressionExtension extends AbstractExtension +final class ExpressionExtension extends AbstractExtension { /** * {@inheritdoc} - * - * @return TwigFunction[] */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('expression', [$this, 'createExpression']), ]; } - public function createExpression($expression) + public function createExpression(string $expression): Expression { return new Expression($expression); } - - /** - * Returns the name of the extension. - * - * @return string The extension name - */ - public function getName() - { - return 'expression'; - } } diff --git a/src/Symfony/Bridge/Twig/Extension/FormExtension.php b/src/Symfony/Bridge/Twig/Extension/FormExtension.php index 174a5cc3fe4bb..0f4076db53275 100644 --- a/src/Symfony/Bridge/Twig/Extension/FormExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/FormExtension.php @@ -15,7 +15,6 @@ use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\FormView; use Twig\Extension\AbstractExtension; -use Twig\TokenParser\TokenParserInterface; use Twig\TwigFilter; use Twig\TwigFunction; use Twig\TwigTest; @@ -25,17 +24,13 @@ * * @author Fabien Potencier * @author Bernhard Schussek - * - * @final since Symfony 4.4 */ -class FormExtension extends AbstractExtension +final class FormExtension extends AbstractExtension { /** * {@inheritdoc} - * - * @return TokenParserInterface[] */ - public function getTokenParsers() + public function getTokenParsers(): array { return [ // {% form_theme form "SomeBundle::widgets.twig" %} @@ -45,10 +40,8 @@ public function getTokenParsers() /** * {@inheritdoc} - * - * @return TwigFunction[] */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('form_widget', null, ['node_class' => 'Symfony\Bridge\Twig\Node\SearchAndRenderBlockNode', 'is_safe' => ['html']]), @@ -67,10 +60,8 @@ public function getFunctions() /** * {@inheritdoc} - * - * @return TwigFilter[] */ - public function getFilters() + public function getFilters(): array { return [ new TwigFilter('humanize', ['Symfony\Component\Form\FormRenderer', 'humanize']), @@ -80,24 +71,14 @@ public function getFilters() /** * {@inheritdoc} - * - * @return TwigTest[] */ - public function getTests() + public function getTests(): array { return [ new TwigTest('selectedchoice', 'Symfony\Bridge\Twig\Extension\twig_is_selected_choice'), new TwigTest('rootform', 'Symfony\Bridge\Twig\Extension\twig_is_root_form'), ]; } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'form'; - } } /** @@ -107,8 +88,6 @@ public function getName() * * @param string|array $selectedValue The selected value to compare * - * @return bool Whether the choice is selected - * * @see ChoiceView::isSelected() */ function twig_is_selected_choice(ChoiceView $choice, $selectedValue): bool diff --git a/src/Symfony/Bridge/Twig/Extension/HttpFoundationExtension.php b/src/Symfony/Bridge/Twig/Extension/HttpFoundationExtension.php index fe9010c21e8b9..a9ee05c4d0093 100644 --- a/src/Symfony/Bridge/Twig/Extension/HttpFoundationExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/HttpFoundationExtension.php @@ -12,9 +12,7 @@ namespace Symfony\Bridge\Twig\Extension; use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpFoundation\UrlHelper; -use Symfony\Component\Routing\RequestContext; use Twig\Extension\AbstractExtension; use Twig\TwigFunction; @@ -22,47 +20,20 @@ * Twig extension for the Symfony HttpFoundation component. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class HttpFoundationExtension extends AbstractExtension +final class HttpFoundationExtension extends AbstractExtension { private $urlHelper; - /** - * @param UrlHelper $urlHelper - */ - public function __construct($urlHelper) + public function __construct(UrlHelper $urlHelper) { - if ($urlHelper instanceof UrlHelper) { - $this->urlHelper = $urlHelper; - - return; - } - - if (!$urlHelper instanceof RequestStack) { - throw new \TypeError(sprintf('The first argument must be an instance of "%s" or an instance of "%s".', UrlHelper::class, RequestStack::class)); - } - - @trigger_error(sprintf('Passing a "%s" instance as the first argument to the "%s" constructor is deprecated since Symfony 4.3, pass a "%s" instance instead.', RequestStack::class, __CLASS__, UrlHelper::class), E_USER_DEPRECATED); - - $requestContext = null; - if (2 === \func_num_args()) { - $requestContext = func_get_arg(1); - if (null !== $requestContext && !$requestContext instanceof RequestContext) { - throw new \TypeError(sprintf('The second argument must be an instance of "%s".', RequestContext::class)); - } - } - - $this->urlHelper = new UrlHelper($urlHelper, $requestContext); + $this->urlHelper = $urlHelper; } /** * {@inheritdoc} - * - * @return TwigFunction[] */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('absolute_url', [$this, 'generateAbsoluteUrl']), @@ -75,13 +46,9 @@ public function getFunctions() * * This method returns the path unchanged if no request is available. * - * @param string $path The path - * - * @return string The absolute URL - * * @see Request::getUriForPath() */ - public function generateAbsoluteUrl($path) + public function generateAbsoluteUrl(string $path): string { return $this->urlHelper->getAbsoluteUrl($path); } @@ -91,24 +58,10 @@ public function generateAbsoluteUrl($path) * * This method returns the path unchanged if no request is available. * - * @param string $path The path - * - * @return string The relative path - * * @see Request::getRelativeUriForPath() */ - public function generateRelativePath($path) + public function generateRelativePath(string $path): string { return $this->urlHelper->getRelativePath($path); } - - /** - * Returns the name of the extension. - * - * @return string The extension name - */ - public function getName() - { - return 'request'; - } } diff --git a/src/Symfony/Bridge/Twig/Extension/HttpKernelExtension.php b/src/Symfony/Bridge/Twig/Extension/HttpKernelExtension.php index 286bc420c66c5..f4b3e4b66953c 100644 --- a/src/Symfony/Bridge/Twig/Extension/HttpKernelExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/HttpKernelExtension.php @@ -19,15 +19,13 @@ * Provides integration with the HttpKernel component. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class HttpKernelExtension extends AbstractExtension +final class HttpKernelExtension extends AbstractExtension { /** - * @return TwigFunction[] + * {@inheritdoc} */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('render', [HttpKernelRuntime::class, 'renderFragment'], ['is_safe' => ['html']]), @@ -36,16 +34,8 @@ public function getFunctions() ]; } - public static function controller($controller, $attributes = [], $query = []) + public static function controller(string $controller, array $attributes = [], array $query = []): ControllerReference { return new ControllerReference($controller, $attributes, $query); } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'http_kernel'; - } } diff --git a/src/Symfony/Bridge/Twig/Extension/HttpKernelRuntime.php b/src/Symfony/Bridge/Twig/Extension/HttpKernelRuntime.php index e0dbb5b356901..6aab9566f9855 100644 --- a/src/Symfony/Bridge/Twig/Extension/HttpKernelRuntime.php +++ b/src/Symfony/Bridge/Twig/Extension/HttpKernelRuntime.php @@ -18,10 +18,8 @@ * Provides integration with the HttpKernel component. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class HttpKernelRuntime +final class HttpKernelRuntime { private $handler; @@ -33,14 +31,11 @@ public function __construct(FragmentHandler $handler) /** * Renders a fragment. * - * @param string|ControllerReference $uri A URI as a string or a ControllerReference instance - * @param array $options An array of options - * - * @return string The fragment content + * @param string|ControllerReference $uri A URI as a string or a ControllerReference instance * * @see FragmentHandler::render() */ - public function renderFragment($uri, $options = []) + public function renderFragment($uri, array $options = []): string { $strategy = isset($options['strategy']) ? $options['strategy'] : 'inline'; unset($options['strategy']); @@ -51,15 +46,11 @@ public function renderFragment($uri, $options = []) /** * Renders a fragment. * - * @param string $strategy A strategy name - * @param string|ControllerReference $uri A URI as a string or a ControllerReference instance - * @param array $options An array of options - * - * @return string The fragment content + * @param string|ControllerReference $uri A URI as a string or a ControllerReference instance * * @see FragmentHandler::render() */ - public function renderFragmentStrategy($strategy, $uri, $options = []) + public function renderFragmentStrategy(string $strategy, $uri, array $options = []): string { return $this->handler->render($uri, $strategy, $options); } diff --git a/src/Symfony/Bridge/Twig/Extension/LogoutUrlExtension.php b/src/Symfony/Bridge/Twig/Extension/LogoutUrlExtension.php index a6648dc072db1..071b9ff247f1d 100644 --- a/src/Symfony/Bridge/Twig/Extension/LogoutUrlExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/LogoutUrlExtension.php @@ -19,10 +19,8 @@ * LogoutUrlHelper provides generator functions for the logout URL to Twig. * * @author Jeremy Mikola - * - * @final since Symfony 4.4 */ -class LogoutUrlExtension extends AbstractExtension +final class LogoutUrlExtension extends AbstractExtension { private $generator; @@ -33,10 +31,8 @@ public function __construct(LogoutUrlGenerator $generator) /** * {@inheritdoc} - * - * @return TwigFunction[] */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('logout_url', [$this, 'getLogoutUrl']), @@ -48,10 +44,8 @@ public function getFunctions() * Generates the relative logout URL for the firewall. * * @param string|null $key The firewall key or null to use the current firewall key - * - * @return string The relative logout URL */ - public function getLogoutPath($key = null) + public function getLogoutPath(string $key = null): string { return $this->generator->getLogoutPath($key); } @@ -60,19 +54,9 @@ public function getLogoutPath($key = null) * Generates the absolute logout URL for the firewall. * * @param string|null $key The firewall key or null to use the current firewall key - * - * @return string The absolute logout URL */ - public function getLogoutUrl($key = null) + public function getLogoutUrl(string $key = null): string { return $this->generator->getLogoutUrl($key); } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'logout_url'; - } } diff --git a/src/Symfony/Bridge/Twig/Extension/ProfilerExtension.php b/src/Symfony/Bridge/Twig/Extension/ProfilerExtension.php index a46f2cdbb8936..fcc4396f1c9a1 100644 --- a/src/Symfony/Bridge/Twig/Extension/ProfilerExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/ProfilerExtension.php @@ -17,10 +17,8 @@ /** * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class ProfilerExtension extends BaseProfilerExtension +final class ProfilerExtension extends BaseProfilerExtension { private $stopwatch; private $events; @@ -33,10 +31,7 @@ public function __construct(Profile $profile, Stopwatch $stopwatch = null) $this->events = new \SplObjectStorage(); } - /** - * @return void - */ - public function enter(Profile $profile) + public function enter(Profile $profile): void { if ($this->stopwatch && $profile->isTemplate()) { $this->events[$profile] = $this->stopwatch->start($profile->getName(), 'template'); @@ -45,10 +40,7 @@ public function enter(Profile $profile) parent::enter($profile); } - /** - * @return void - */ - public function leave(Profile $profile) + public function leave(Profile $profile): void { parent::leave($profile); @@ -57,12 +49,4 @@ public function leave(Profile $profile) unset($this->events[$profile]); } } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'native_profiler'; - } } diff --git a/src/Symfony/Bridge/Twig/Extension/RoutingExtension.php b/src/Symfony/Bridge/Twig/Extension/RoutingExtension.php index 1ba528546d6d2..800c22f6d4c2c 100644 --- a/src/Symfony/Bridge/Twig/Extension/RoutingExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/RoutingExtension.php @@ -22,10 +22,8 @@ * Provides integration of the Routing component with Twig. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class RoutingExtension extends AbstractExtension +final class RoutingExtension extends AbstractExtension { private $generator; @@ -36,10 +34,8 @@ public function __construct(UrlGeneratorInterface $generator) /** * {@inheritdoc} - * - * @return TwigFunction[] */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('url', [$this, 'getUrl'], ['is_safe_callback' => [$this, 'isUrlGenerationSafe']]), @@ -47,26 +43,12 @@ public function getFunctions() ]; } - /** - * @param string $name - * @param array $parameters - * @param bool $relative - * - * @return string - */ - public function getPath($name, $parameters = [], $relative = false) + public function getPath(string $name, array $parameters = [], bool $relative = false): string { return $this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH); } - /** - * @param string $name - * @param array $parameters - * @param bool $schemeRelative - * - * @return string - */ - public function getUrl($name, $parameters = [], $schemeRelative = false) + public function getUrl(string $name, array $parameters = [], bool $schemeRelative = false): string { return $this->generator->generate($name, $parameters, $schemeRelative ? UrlGeneratorInterface::NETWORK_PATH : UrlGeneratorInterface::ABSOLUTE_URL); } @@ -92,8 +74,6 @@ public function getUrl($name, $parameters = [], $schemeRelative = false) * @param Node $argsNode The arguments of the path/url function * * @return array An array with the contexts the URL is safe - * - * @final */ public function isUrlGenerationSafe(Node $argsNode): array { @@ -110,12 +90,4 @@ public function isUrlGenerationSafe(Node $argsNode): array return []; } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'routing'; - } } diff --git a/src/Symfony/Bridge/Twig/Extension/SecurityExtension.php b/src/Symfony/Bridge/Twig/Extension/SecurityExtension.php index 4acd7bbf9cc72..c70e0bb646d29 100644 --- a/src/Symfony/Bridge/Twig/Extension/SecurityExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/SecurityExtension.php @@ -21,10 +21,8 @@ * SecurityExtension exposes security context features. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class SecurityExtension extends AbstractExtension +final class SecurityExtension extends AbstractExtension { private $securityChecker; @@ -33,7 +31,7 @@ public function __construct(AuthorizationCheckerInterface $securityChecker = nul $this->securityChecker = $securityChecker; } - public function isGranted($role, $object = null, $field = null) + public function isGranted($role, object $object = null, string $field = null): bool { if (null === $this->securityChecker) { return false; @@ -52,21 +50,11 @@ public function isGranted($role, $object = null, $field = null) /** * {@inheritdoc} - * - * @return TwigFunction[] */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('is_granted', [$this, 'isGranted']), ]; } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'security'; - } } diff --git a/src/Symfony/Bridge/Twig/Extension/StopwatchExtension.php b/src/Symfony/Bridge/Twig/Extension/StopwatchExtension.php index f4b9a24ced5cd..80a25a949bdb5 100644 --- a/src/Symfony/Bridge/Twig/Extension/StopwatchExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/StopwatchExtension.php @@ -20,10 +20,8 @@ * Twig extension for the stopwatch helper. * * @author Wouter J - * - * @final since Symfony 4.4 */ -class StopwatchExtension extends AbstractExtension +final class StopwatchExtension extends AbstractExtension { private $stopwatch; private $enabled; @@ -34,7 +32,7 @@ public function __construct(Stopwatch $stopwatch = null, bool $enabled = true) $this->enabled = $enabled; } - public function getStopwatch() + public function getStopwatch(): Stopwatch { return $this->stopwatch; } @@ -42,7 +40,7 @@ public function getStopwatch() /** * @return TokenParserInterface[] */ - public function getTokenParsers() + public function getTokenParsers(): array { return [ /* @@ -53,9 +51,4 @@ public function getTokenParsers() new StopwatchTokenParser(null !== $this->stopwatch && $this->enabled), ]; } - - public function getName() - { - return 'stopwatch'; - } } diff --git a/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php b/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php index bd3c2eb8932d1..aa5a2dde3d746 100644 --- a/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/TranslationExtension.php @@ -13,45 +13,31 @@ use Symfony\Bridge\Twig\NodeVisitor\TranslationDefaultDomainNodeVisitor; use Symfony\Bridge\Twig\NodeVisitor\TranslationNodeVisitor; -use Symfony\Bridge\Twig\TokenParser\TransChoiceTokenParser; use Symfony\Bridge\Twig\TokenParser\TransDefaultDomainTokenParser; use Symfony\Bridge\Twig\TokenParser\TransTokenParser; -use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface; use Symfony\Contracts\Translation\TranslatorInterface; use Symfony\Contracts\Translation\TranslatorTrait; use Twig\Extension\AbstractExtension; use Twig\NodeVisitor\NodeVisitorInterface; -use Twig\TokenParser\AbstractTokenParser; use Twig\TwigFilter; /** * Provides integration of the Translation component with Twig. * * @author Fabien Potencier - * - * @final since Symfony 4.2 */ -class TranslationExtension extends AbstractExtension +final class TranslationExtension extends AbstractExtension { private $translator; private $translationNodeVisitor; - /** - * @param TranslatorInterface|null $translator - */ - public function __construct($translator = null, NodeVisitorInterface $translationNodeVisitor = null) + public function __construct(TranslatorInterface $translator = null, NodeVisitorInterface $translationNodeVisitor = null) { - if (null !== $translator && !$translator instanceof LegacyTranslatorInterface && !$translator instanceof TranslatorInterface) { - throw new \TypeError(sprintf('Argument 1 passed to %s() must be an instance of %s, %s given.', __METHOD__, TranslatorInterface::class, \is_object($translator) ? \get_class($translator) : \gettype($translator))); - } $this->translator = $translator; $this->translationNodeVisitor = $translationNodeVisitor; } - /** - * @return TranslatorInterface|null - */ - public function getTranslator() + public function getTranslator(): TranslatorInterface { if (null === $this->translator) { if (!interface_exists(TranslatorInterface::class)) { @@ -68,33 +54,23 @@ public function getTranslator() /** * {@inheritdoc} - * - * @return TwigFilter[] */ - public function getFilters() + public function getFilters(): array { return [ new TwigFilter('trans', [$this, 'trans']), - new TwigFilter('transchoice', [$this, 'transchoice'], ['deprecated' => '4.2', 'alternative' => 'trans" with parameter "%count%']), ]; } /** - * Returns the token parser instance to add to the existing list. - * - * @return AbstractTokenParser[] + * {@inheritdoc} */ - public function getTokenParsers() + public function getTokenParsers(): array { return [ // {% trans %}Symfony is great!{% endtrans %} new TransTokenParser(), - // {% transchoice count %} - // {0} There is no apples|{1} There is one apple|]1,Inf] There is {{ count }} apples - // {% endtranschoice %} - new TransChoiceTokenParser(), - // {% trans_default_domain "foobar" %} new TransDefaultDomainTokenParser(), ]; @@ -102,20 +78,18 @@ public function getTokenParsers() /** * {@inheritdoc} - * - * @return NodeVisitorInterface[] */ - public function getNodeVisitors() + public function getNodeVisitors(): array { return [$this->getTranslationNodeVisitor(), new TranslationDefaultDomainNodeVisitor()]; } - public function getTranslationNodeVisitor() + public function getTranslationNodeVisitor(): TranslationNodeVisitor { return $this->translationNodeVisitor ?: $this->translationNodeVisitor = new TranslationNodeVisitor(); } - public function trans($message, array $arguments = [], $domain = null, $locale = null, $count = null) + public function trans(string $message, array $arguments = [], string $domain = null, string $locale = null, int $count = null): string { if (null !== $count) { $arguments['%count%'] = $count; @@ -123,26 +97,4 @@ public function trans($message, array $arguments = [], $domain = null, $locale = return $this->getTranslator()->trans($message, $arguments, $domain, $locale); } - - /** - * @deprecated since Symfony 4.2, use the trans() method instead with a %count% parameter - */ - public function transchoice($message, $count, array $arguments = [], $domain = null, $locale = null) - { - $translator = $this->getTranslator(); - - if ($translator instanceof TranslatorInterface) { - return $translator->trans($message, array_merge(['%count%' => $count], $arguments), $domain, $locale); - } - - return $translator->transChoice($message, $count, array_merge(['%count%' => $count], $arguments), $domain, $locale); - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'translator'; - } } diff --git a/src/Symfony/Bridge/Twig/Extension/WebLinkExtension.php b/src/Symfony/Bridge/Twig/Extension/WebLinkExtension.php index c2c6f8ba8fcf6..4b8217d932f4e 100644 --- a/src/Symfony/Bridge/Twig/Extension/WebLinkExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/WebLinkExtension.php @@ -21,10 +21,8 @@ * Twig extension for the Symfony WebLink component. * * @author Kévin Dunglas - * - * @final since Symfony 4.4 */ -class WebLinkExtension extends AbstractExtension +final class WebLinkExtension extends AbstractExtension { private $requestStack; @@ -35,10 +33,8 @@ public function __construct(RequestStack $requestStack) /** * {@inheritdoc} - * - * @return TwigFunction[] */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('link', [$this, 'link']), @@ -53,13 +49,12 @@ public function getFunctions() /** * Adds a "Link" HTTP header. * - * @param string $uri The relation URI * @param string $rel The relation type (e.g. "preload", "prefetch", "prerender" or "dns-prefetch") * @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]") * * @return string The relation URI */ - public function link($uri, $rel, array $attributes = []) + public function link(string $uri, string $rel, array $attributes = []): string { if (!$request = $this->requestStack->getMasterRequest()) { return $uri; @@ -79,12 +74,11 @@ public function link($uri, $rel, array $attributes = []) /** * Preloads a resource. * - * @param string $uri A public path - * @param array $attributes The attributes of this link (e.g. "['as' => true]", "['crossorigin' => 'use-credentials']") + * @param array $attributes The attributes of this link (e.g. "['as' => true]", "['crossorigin' => 'use-credentials']") * * @return string The path of the asset */ - public function preload($uri, array $attributes = []) + public function preload(string $uri, array $attributes = []): string { return $this->link($uri, 'preload', $attributes); } @@ -92,12 +86,11 @@ public function preload($uri, array $attributes = []) /** * Resolves a resource origin as early as possible. * - * @param string $uri A public path - * @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]") + * @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]") * * @return string The path of the asset */ - public function dnsPrefetch($uri, array $attributes = []) + public function dnsPrefetch(string $uri, array $attributes = []): string { return $this->link($uri, 'dns-prefetch', $attributes); } @@ -105,12 +98,11 @@ public function dnsPrefetch($uri, array $attributes = []) /** * Initiates a early connection to a resource (DNS resolution, TCP handshake, TLS negotiation). * - * @param string $uri A public path - * @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]") + * @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]") * * @return string The path of the asset */ - public function preconnect($uri, array $attributes = []) + public function preconnect(string $uri, array $attributes = []): string { return $this->link($uri, 'preconnect', $attributes); } @@ -118,12 +110,11 @@ public function preconnect($uri, array $attributes = []) /** * Indicates to the client that it should prefetch this resource. * - * @param string $uri A public path - * @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]") + * @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]") * * @return string The path of the asset */ - public function prefetch($uri, array $attributes = []) + public function prefetch(string $uri, array $attributes = []): string { return $this->link($uri, 'prefetch', $attributes); } @@ -131,12 +122,11 @@ public function prefetch($uri, array $attributes = []) /** * Indicates to the client that it should prerender this resource . * - * @param string $uri A public path - * @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]") + * @param array $attributes The attributes of this link (e.g. "['as' => true]", "['pr' => 0.5]") * * @return string The path of the asset */ - public function prerender($uri, array $attributes = []) + public function prerender(string $uri, array $attributes = []): string { return $this->link($uri, 'prerender', $attributes); } diff --git a/src/Symfony/Bridge/Twig/Extension/WorkflowExtension.php b/src/Symfony/Bridge/Twig/Extension/WorkflowExtension.php index d5a2e759aa34a..d385567b13501 100644 --- a/src/Symfony/Bridge/Twig/Extension/WorkflowExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/WorkflowExtension.php @@ -21,10 +21,8 @@ * WorkflowExtension. * * @author Grégoire Pineau - * - * @final since Symfony 4.4 */ -class WorkflowExtension extends AbstractExtension +final class WorkflowExtension extends AbstractExtension { private $workflowRegistry; @@ -34,9 +32,9 @@ public function __construct(Registry $workflowRegistry) } /** - * @return TwigFunction[] + * {@inheritdoc} */ - public function getFunctions() + public function getFunctions(): array { return [ new TwigFunction('workflow_can', [$this, 'canTransition']), @@ -50,14 +48,8 @@ public function getFunctions() /** * Returns true if the transition is enabled. - * - * @param object $subject A subject - * @param string $transitionName A transition - * @param string $name A workflow name - * - * @return bool true if the transition is enabled */ - public function canTransition($subject, $transitionName, $name = null) + public function canTransition(object $subject, string $transitionName, string $name = null): bool { return $this->workflowRegistry->get($subject, $name)->can($subject, $transitionName); } @@ -65,26 +57,17 @@ public function canTransition($subject, $transitionName, $name = null) /** * Returns all enabled transitions. * - * @param object $subject A subject - * @param string $name A workflow name - * * @return Transition[] All enabled transitions */ - public function getEnabledTransitions($subject, $name = null) + public function getEnabledTransitions(object $subject, string $name = null): array { return $this->workflowRegistry->get($subject, $name)->getEnabledTransitions($subject); } /** * Returns true if the place is marked. - * - * @param object $subject A subject - * @param string $placeName A place name - * @param string $name A workflow name - * - * @return bool true if the transition is enabled */ - public function hasMarkedPlace($subject, $placeName, $name = null) + public function hasMarkedPlace(object $subject, string $placeName, string $name = null): bool { return $this->workflowRegistry->get($subject, $name)->getMarking($subject)->has($placeName); } @@ -92,13 +75,9 @@ public function hasMarkedPlace($subject, $placeName, $name = null) /** * Returns marked places. * - * @param object $subject A subject - * @param bool $placesNameOnly If true, returns only places name. If false returns the raw representation - * @param string $name A workflow name - * * @return string[]|int[] */ - public function getMarkedPlaces($subject, $placesNameOnly = true, $name = null) + public function getMarkedPlaces(object $subject, bool $placesNameOnly = true, string $name = null): array { $places = $this->workflowRegistry->get($subject, $name)->getMarking($subject)->getPlaces(); @@ -112,12 +91,11 @@ public function getMarkedPlaces($subject, $placesNameOnly = true, $name = null) /** * Returns the metadata for a specific subject. * - * @param object $subject A subject * @param string|Transition|null $metadataSubject Use null to get workflow metadata * Use a string (the place name) to get place metadata * Use a Transition instance to get transition metadata */ - public function getMetadata($subject, string $key, $metadataSubject = null, string $name = null): ?string + public function getMetadata(object $subject, string $key, $metadataSubject = null, string $name = null): ?string { return $this ->workflowRegistry @@ -127,15 +105,10 @@ public function getMetadata($subject, string $key, $metadataSubject = null, stri ; } - public function buildTransitionBlockerList($subject, string $transitionName, string $name = null): TransitionBlockerList + public function buildTransitionBlockerList(object $subject, string $transitionName, string $name = null): TransitionBlockerList { $workflow = $this->workflowRegistry->get($subject, $name); return $workflow->buildTransitionBlockerList($subject, $transitionName); } - - public function getName() - { - return 'workflow'; - } } diff --git a/src/Symfony/Bridge/Twig/Extension/YamlExtension.php b/src/Symfony/Bridge/Twig/Extension/YamlExtension.php index 02d19d8ae3d3b..63df1336030bf 100644 --- a/src/Symfony/Bridge/Twig/Extension/YamlExtension.php +++ b/src/Symfony/Bridge/Twig/Extension/YamlExtension.php @@ -12,7 +12,6 @@ namespace Symfony\Bridge\Twig\Extension; use Symfony\Component\Yaml\Dumper as YamlDumper; -use Symfony\Component\Yaml\Yaml; use Twig\Extension\AbstractExtension; use Twig\TwigFilter; @@ -20,17 +19,13 @@ * Provides integration of the Yaml component with Twig. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class YamlExtension extends AbstractExtension +final class YamlExtension extends AbstractExtension { /** * {@inheritdoc} - * - * @return TwigFilter[] */ - public function getFilters() + public function getFilters(): array { return [ new TwigFilter('yaml_encode', [$this, 'encode']), @@ -38,7 +33,7 @@ public function getFilters() ]; } - public function encode($input, $inline = 0, $dumpObjects = 0) + public function encode($input, int $inline = 0, int $dumpObjects = 0): string { static $dumper; @@ -53,7 +48,7 @@ public function encode($input, $inline = 0, $dumpObjects = 0) return $dumper->dump($input, $inline, 0, false, $dumpObjects); } - public function dump($value, $inline = 0, $dumpObjects = false) + public function dump($value, int $inline = 0, int $dumpObjects = 0): string { if (\is_resource($value)) { return '%Resource%'; @@ -65,12 +60,4 @@ public function dump($value, $inline = 0, $dumpObjects = false) return $this->encode($value, $inline, $dumpObjects); } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'yaml'; - } } diff --git a/src/Symfony/Bridge/Twig/Form/TwigRendererEngine.php b/src/Symfony/Bridge/Twig/Form/TwigRendererEngine.php index 1e97ce3371d1d..bc3b82d2f595f 100644 --- a/src/Symfony/Bridge/Twig/Form/TwigRendererEngine.php +++ b/src/Symfony/Bridge/Twig/Form/TwigRendererEngine.php @@ -40,7 +40,7 @@ public function __construct(array $defaultThemes, Environment $environment) /** * {@inheritdoc} */ - public function renderBlock(FormView $view, $resource, $blockName, array $variables = []) + public function renderBlock(FormView $view, $resource, string $blockName, array $variables = []) { $cacheKey = $view->vars[self::CACHE_KEY_VAR]; @@ -70,13 +70,9 @@ public function renderBlock(FormView $view, $resource, $blockName, array $variab * * @see getResourceForBlock() * - * @param string $cacheKey The cache key of the form view - * @param FormView $view The form view for finding the applying themes - * @param string $blockName The name of the block to load - * * @return bool True if the resource could be loaded, false otherwise */ - protected function loadResourceForBlockName($cacheKey, FormView $view, $blockName) + protected function loadResourceForBlockName(string $cacheKey, FormView $view, string $blockName) { // The caller guarantees that $this->resources[$cacheKey][$block] is // not set, but it doesn't have to check whether $this->resources[$cacheKey] @@ -143,14 +139,13 @@ protected function loadResourceForBlockName($cacheKey, FormView $view, $blockNam /** * Loads the resources for all blocks in a theme. * - * @param string $cacheKey The cache key for storing the resource - * @param mixed $theme The theme to load the block from. This parameter - * is passed by reference, because it might be necessary - * to initialize the theme first. Any changes made to - * this variable will be kept and be available upon - * further calls to this method using the same theme. + * @param mixed $theme The theme to load the block from. This parameter + * is passed by reference, because it might be necessary + * to initialize the theme first. Any changes made to + * this variable will be kept and be available upon + * further calls to this method using the same theme. */ - protected function loadResourcesFromTheme($cacheKey, &$theme) + protected function loadResourcesFromTheme(string $cacheKey, &$theme) { if (!$theme instanceof Template) { /* @var Template $theme */ diff --git a/src/Symfony/Bridge/Twig/Node/DumpNode.php b/src/Symfony/Bridge/Twig/Node/DumpNode.php index d82d9ade1feaf..e94f1b7189f69 100644 --- a/src/Symfony/Bridge/Twig/Node/DumpNode.php +++ b/src/Symfony/Bridge/Twig/Node/DumpNode.php @@ -16,14 +16,12 @@ /** * @author Julien Galenski - * - * @final since Symfony 4.4 */ -class DumpNode extends Node +final class DumpNode extends Node { private $varPrefix; - public function __construct($varPrefix, Node $values = null, int $lineno, string $tag = null) + public function __construct($varPrefix, ?Node $values, int $lineno, string $tag = null) { $nodes = []; if (null !== $values) { @@ -37,7 +35,7 @@ public function __construct($varPrefix, Node $values = null, int $lineno, string /** * @return void */ - public function compile(Compiler $compiler) + public function compile(Compiler $compiler): void { $compiler ->write("if (\$this->env->isDebug()) {\n") diff --git a/src/Symfony/Bridge/Twig/Node/FormThemeNode.php b/src/Symfony/Bridge/Twig/Node/FormThemeNode.php index b17243060f302..e37311267bb17 100644 --- a/src/Symfony/Bridge/Twig/Node/FormThemeNode.php +++ b/src/Symfony/Bridge/Twig/Node/FormThemeNode.php @@ -17,20 +17,15 @@ /** * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class FormThemeNode extends Node +final class FormThemeNode extends Node { public function __construct(Node $form, Node $resources, int $lineno, string $tag = null, bool $only = false) { parent::__construct(['form' => $form, 'resources' => $resources], ['only' => $only], $lineno, $tag); } - /** - * @return void - */ - public function compile(Compiler $compiler) + public function compile(Compiler $compiler): void { $compiler ->addDebugInfo($this) diff --git a/src/Symfony/Bridge/Twig/Node/RenderBlockNode.php b/src/Symfony/Bridge/Twig/Node/RenderBlockNode.php index 29402a8024fae..4d4cf61365772 100644 --- a/src/Symfony/Bridge/Twig/Node/RenderBlockNode.php +++ b/src/Symfony/Bridge/Twig/Node/RenderBlockNode.php @@ -21,15 +21,10 @@ * is "foo", the block "foo" will be rendered. * * @author Bernhard Schussek - * - * @final since Symfony 4.4 */ -class RenderBlockNode extends FunctionExpression +final class RenderBlockNode extends FunctionExpression { - /** - * @return void - */ - public function compile(Compiler $compiler) + public function compile(Compiler $compiler): void { $compiler->addDebugInfo($this); $arguments = iterator_to_array($this->getNode('arguments')); diff --git a/src/Symfony/Bridge/Twig/Node/SearchAndRenderBlockNode.php b/src/Symfony/Bridge/Twig/Node/SearchAndRenderBlockNode.php index 5db8d92244899..39cc1f7ffe939 100644 --- a/src/Symfony/Bridge/Twig/Node/SearchAndRenderBlockNode.php +++ b/src/Symfony/Bridge/Twig/Node/SearchAndRenderBlockNode.php @@ -18,15 +18,10 @@ /** * @author Bernhard Schussek - * - * @final since Symfony 4.4 */ -class SearchAndRenderBlockNode extends FunctionExpression +final class SearchAndRenderBlockNode extends FunctionExpression { - /** - * @return void - */ - public function compile(Compiler $compiler) + public function compile(Compiler $compiler): void { $compiler->addDebugInfo($this); $compiler->raw('$this->env->getRuntime(\'Symfony\Component\Form\FormRenderer\')->searchAndRenderBlock('); diff --git a/src/Symfony/Bridge/Twig/Node/StopwatchNode.php b/src/Symfony/Bridge/Twig/Node/StopwatchNode.php index b4dd8a9b37b4f..cfa4d8a197f9b 100644 --- a/src/Symfony/Bridge/Twig/Node/StopwatchNode.php +++ b/src/Symfony/Bridge/Twig/Node/StopwatchNode.php @@ -19,20 +19,15 @@ * Represents a stopwatch node. * * @author Wouter J - * - * @final since Symfony 4.4 */ -class StopwatchNode extends Node +final class StopwatchNode extends Node { public function __construct(Node $name, Node $body, AssignNameExpression $var, int $lineno = 0, string $tag = null) { parent::__construct(['body' => $body, 'name' => $name, 'var' => $var], [], $lineno, $tag); } - /** - * @return void - */ - public function compile(Compiler $compiler) + public function compile(Compiler $compiler): void { $compiler ->addDebugInfo($this) diff --git a/src/Symfony/Bridge/Twig/Node/TransDefaultDomainNode.php b/src/Symfony/Bridge/Twig/Node/TransDefaultDomainNode.php index 49ceac1404c5e..df29f0a19931f 100644 --- a/src/Symfony/Bridge/Twig/Node/TransDefaultDomainNode.php +++ b/src/Symfony/Bridge/Twig/Node/TransDefaultDomainNode.php @@ -17,20 +17,15 @@ /** * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class TransDefaultDomainNode extends Node +final class TransDefaultDomainNode extends Node { public function __construct(AbstractExpression $expr, int $lineno = 0, string $tag = null) { parent::__construct(['expr' => $expr], [], $lineno, $tag); } - /** - * @return void - */ - public function compile(Compiler $compiler) + public function compile(Compiler $compiler): void { // noop as this node is just a marker for TranslationDefaultDomainNodeVisitor } diff --git a/src/Symfony/Bridge/Twig/Node/TransNode.php b/src/Symfony/Bridge/Twig/Node/TransNode.php index 0a754fa859858..da2b85d1c2861 100644 --- a/src/Symfony/Bridge/Twig/Node/TransNode.php +++ b/src/Symfony/Bridge/Twig/Node/TransNode.php @@ -19,15 +19,10 @@ use Twig\Node\Node; use Twig\Node\TextNode; -// BC/FC with namespaced Twig -class_exists('Twig\Node\Expression\ArrayExpression'); - /** * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class TransNode extends Node +final class TransNode extends Node { public function __construct(Node $body, Node $domain = null, AbstractExpression $count = null, AbstractExpression $vars = null, AbstractExpression $locale = null, int $lineno = 0, string $tag = null) { @@ -48,10 +43,7 @@ public function __construct(Node $body, Node $domain = null, AbstractExpression parent::__construct($nodes, [], $lineno, $tag); } - /** - * @return void - */ - public function compile(Compiler $compiler) + public function compile(Compiler $compiler): void { $compiler->addDebugInfo($this); @@ -108,7 +100,7 @@ public function compile(Compiler $compiler) $compiler->raw(");\n"); } - protected function compileString(Node $body, ArrayExpression $vars, $ignoreStrictCheck = false) + private function compileString(Node $body, ArrayExpression $vars, bool $ignoreStrictCheck = false): array { if ($body instanceof ConstantExpression) { $msg = $body->getAttribute('value'); diff --git a/src/Symfony/Bridge/Twig/NodeVisitor/Scope.php b/src/Symfony/Bridge/Twig/NodeVisitor/Scope.php index 642623f2a693c..765b4b69bd88c 100644 --- a/src/Symfony/Bridge/Twig/NodeVisitor/Scope.php +++ b/src/Symfony/Bridge/Twig/NodeVisitor/Scope.php @@ -50,14 +50,11 @@ public function leave() /** * Stores data into current scope. * - * @param string $key - * @param mixed $value - * * @return $this * * @throws \LogicException */ - public function set($key, $value) + public function set(string $key, $value) { if ($this->left) { throw new \LogicException('Left scope is not mutable.'); @@ -71,11 +68,9 @@ public function set($key, $value) /** * Tests if a data is visible from current scope. * - * @param string $key - * * @return bool */ - public function has($key) + public function has(string $key) { if (\array_key_exists($key, $this->data)) { return true; @@ -91,12 +86,9 @@ public function has($key) /** * Returns data visible from current scope. * - * @param string $key - * @param mixed $default - * * @return mixed */ - public function get($key, $default = null) + public function get(string $key, $default = null) { if (\array_key_exists($key, $this->data)) { return $this->data[$key]; diff --git a/src/Symfony/Bridge/Twig/NodeVisitor/TranslationDefaultDomainNodeVisitor.php b/src/Symfony/Bridge/Twig/NodeVisitor/TranslationDefaultDomainNodeVisitor.php index 72badea2d2bd0..d8a791b3a40b8 100644 --- a/src/Symfony/Bridge/Twig/NodeVisitor/TranslationDefaultDomainNodeVisitor.php +++ b/src/Symfony/Bridge/Twig/NodeVisitor/TranslationDefaultDomainNodeVisitor.php @@ -27,10 +27,8 @@ /** * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class TranslationDefaultDomainNodeVisitor extends AbstractNodeVisitor +final class TranslationDefaultDomainNodeVisitor extends AbstractNodeVisitor { private $scope; @@ -41,10 +39,8 @@ public function __construct() /** * {@inheritdoc} - * - * @return Node */ - protected function doEnterNode(Node $node, Environment $env) + protected function doEnterNode(Node $node, Environment $env): Node { if ($node instanceof BlockNode || $node instanceof ModuleNode) { $this->scope = $this->scope->enter(); @@ -95,10 +91,8 @@ protected function doEnterNode(Node $node, Environment $env) /** * {@inheritdoc} - * - * @return Node|null */ - protected function doLeaveNode(Node $node, Environment $env) + protected function doLeaveNode(Node $node, Environment $env): ?Node { if ($node instanceof TransDefaultDomainNode) { return null; @@ -116,7 +110,7 @@ protected function doLeaveNode(Node $node, Environment $env) * * @return int */ - public function getPriority() + public function getPriority(): int { return -10; } diff --git a/src/Symfony/Bridge/Twig/NodeVisitor/TranslationNodeVisitor.php b/src/Symfony/Bridge/Twig/NodeVisitor/TranslationNodeVisitor.php index a72697deb37e2..2764afc0a402c 100644 --- a/src/Symfony/Bridge/Twig/NodeVisitor/TranslationNodeVisitor.php +++ b/src/Symfony/Bridge/Twig/NodeVisitor/TranslationNodeVisitor.php @@ -22,45 +22,35 @@ * TranslationNodeVisitor extracts translation messages. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class TranslationNodeVisitor extends AbstractNodeVisitor +final class TranslationNodeVisitor extends AbstractNodeVisitor { const UNDEFINED_DOMAIN = '_undefined'; private $enabled = false; private $messages = []; - /** - * @return void - */ - public function enable() + public function enable(): void { $this->enabled = true; $this->messages = []; } - /** - * @return void - */ - public function disable() + public function disable(): void { $this->enabled = false; $this->messages = []; } - public function getMessages() + public function getMessages(): array { return $this->messages; } /** * {@inheritdoc} - * - * @return Node */ - protected function doEnterNode(Node $node, Environment $env) + protected function doEnterNode(Node $node, Environment $env): Node { if (!$this->enabled) { return $node; @@ -99,10 +89,8 @@ protected function doEnterNode(Node $node, Environment $env) /** * {@inheritdoc} - * - * @return Node|null */ - protected function doLeaveNode(Node $node, Environment $env) + protected function doLeaveNode(Node $node, Environment $env): ?Node { return $node; } @@ -112,7 +100,7 @@ protected function doLeaveNode(Node $node, Environment $env) * * @return int */ - public function getPriority() + public function getPriority(): int { return 0; } diff --git a/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php b/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php index 3d85565fdc59f..5676e8c91c476 100644 --- a/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Command/DebugCommandTest.php @@ -63,32 +63,6 @@ public function testWarningsWrongBundleOverriding() $this->assertEquals($expected, json_decode($tester->getDisplay(true), true)); } - /** - * @group legacy - * @expectedDeprecation Loading Twig templates from the "%sResources/BarBundle/views" directory is deprecated since Symfony 4.2, use "%stemplates/bundles/BarBundle" instead. - */ - public function testDeprecationForWrongBundleOverridingInLegacyPath() - { - $bundleMetadata = [ - 'TwigBundle' => 'vendor/twig-bundle/', - 'WebProfilerBundle' => 'vendor/web-profiler-bundle/', - ]; - $defaultPath = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'.\DIRECTORY_SEPARATOR.'templates'; - $rootDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'; - - $tester = $this->createCommandTester([], $bundleMetadata, $defaultPath, $rootDir); - $ret = $tester->execute(['--filter' => 'unknown', '--format' => 'json'], ['decorated' => false]); - - $expected = ['warnings' => [ - 'Path "Resources/BarBundle" not matching any bundle found', - 'Path "templates/bundles/UnknownBundle" not matching any bundle found', - 'Path "templates/bundles/WebProfileBundle" not matching any bundle found, did you mean "WebProfilerBundle"?', - ]]; - - $this->assertEquals(0, $ret, 'Returns 0 in case of success'); - $this->assertEquals($expected, json_decode($tester->getDisplay(true), true)); - } - public function testMalformedTemplateName() { $this->expectException('Symfony\Component\Console\Exception\InvalidArgumentException'); @@ -280,7 +254,7 @@ public function getDebugTemplateNameTestData() public function testDebugTemplateNameWithChainLoader() { - $tester = $this->createCommandTester(['templates/' => null], [], null, null, true); + $tester = $this->createCommandTester(['templates/' => null], [], null, true); $ret = $tester->execute(['name' => 'base.html.twig'], ['decorated' => false]); $this->assertEquals(0, $ret, 'Returns 0 in case of success'); @@ -290,7 +264,7 @@ public function testDebugTemplateNameWithChainLoader() public function testWithGlobals() { $message = 'foo'; - $tester = $this->createCommandTester([], [], null, null, false, ['message' => $message]); + $tester = $this->createCommandTester([], [], null, false, ['message' => $message]); $tester->execute([], ['decorated' => true]); $display = $tester->getDisplay(); $this->assertStringContainsString(json_encode($message), $display); @@ -299,7 +273,7 @@ public function testWithGlobals() public function testWithGlobalsJson() { $globals = ['message' => 'foo']; - $tester = $this->createCommandTester([], [], null, null, false, $globals); + $tester = $this->createCommandTester([], [], null, false, $globals); $tester->execute(['--format' => 'json'], ['decorated' => true]); $display = $tester->getDisplay(); $display = json_decode($display, true); @@ -318,7 +292,7 @@ public function testWithFilter() $this->assertNotSame($display1, $display2); } - private function createCommandTester(array $paths = [], array $bundleMetadata = [], string $defaultPath = null, string $rootDir = null, bool $useChainLoader = false, array $globals = []): CommandTester + private function createCommandTester(array $paths = [], array $bundleMetadata = [], string $defaultPath = null, bool $useChainLoader = false, array $globals = []): CommandTester { $projectDir = \dirname(__DIR__).\DIRECTORY_SEPARATOR.'Fixtures'; $loader = new FilesystemLoader([], $projectDir); @@ -340,7 +314,7 @@ private function createCommandTester(array $paths = [], array $bundleMetadata = } $application = new Application(); - $application->add(new DebugCommand($environment, $projectDir, $bundleMetadata, $defaultPath, null, $rootDir)); + $application->add(new DebugCommand($environment, $projectDir, $bundleMetadata, $defaultPath, null)); $command = $application->find('debug:twig'); return new CommandTester($command); diff --git a/src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php b/src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php index 46c0883722a20..8905068405197 100644 --- a/src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Command/LintCommandTest.php @@ -66,9 +66,6 @@ public function testLintFileCompileTimeException() $this->assertRegExp('/ERROR in \S+ \(line /', trim($tester->getDisplay())); } - /** - * @group tty - */ public function testLintDefaultPaths() { $tester = $this->createCommandTester(); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/AbstractBootstrap3LayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/AbstractBootstrap3LayoutTest.php index 66654d9ce5890..8f38c8486ffda 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/AbstractBootstrap3LayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/AbstractBootstrap3LayoutTest.php @@ -1691,28 +1691,9 @@ public function testDateTimeWithWidgetSingleText() ); } - /** - * @group legacy - */ public function testDateTimeWithWidgetSingleTextIgnoreDateAndTimeWidgets() { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\DateTimeType', '2011-02-03 04:05:06', [ - 'input' => 'string', - 'date_widget' => 'choice', - 'time_widget' => 'choice', - 'widget' => 'single_text', - 'model_timezone' => 'UTC', - 'view_timezone' => 'UTC', - ]); - - $this->assertWidgetMatchesXpath($form->createView(), ['attr' => ['class' => 'my&class']], -'/input - [@type="datetime-local"] - [@name="name"] - [@class="my&class form-control"] - [@value="2011-02-03T04:05:06"] -' - ); + $this->markTestSkipped('Make tests pass with symfony/form 4.4'); } public function testDateChoice() diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/CodeExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/CodeExtensionTest.php index 874faeeb99955..33bb266cb6a2f 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/CodeExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/CodeExtensionTest.php @@ -44,7 +44,7 @@ public function testGettingMethodAbbreviation($method, $abbr) $this->assertEquals($this->getExtension()->abbrMethod($method), $abbr); } - public function getClassNameProvider() + public function getClassNameProvider(): array { return [ ['F\Q\N\Foo', 'Foo'], @@ -52,7 +52,7 @@ public function getClassNameProvider() ]; } - public function getMethodNameProvider() + public function getMethodNameProvider(): array { return [ ['F\Q\N\Foo::Method', 'Foo::Method()'], @@ -62,12 +62,7 @@ public function getMethodNameProvider() ]; } - public function testGetName() - { - $this->assertEquals('code', $this->getExtension()->getName()); - } - - protected function getExtension() + protected function getExtension(): CodeExtension { return new CodeExtension(new FileLinkFormatter('proto://%f#&line=%l&'.substr(__FILE__, 0, 5).'>foobar'), \DIRECTORY_SEPARATOR.'project', 'UTF-8'); } diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubFilesystemLoader.php b/src/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubFilesystemLoader.php deleted file mode 100644 index 8ee7830974861..0000000000000 --- a/src/Symfony/Bridge/Twig/Tests/Extension/Fixtures/StubFilesystemLoader.php +++ /dev/null @@ -1,28 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bridge\Twig\Tests\Extension\Fixtures; - -use Twig\Loader\FilesystemLoader; - -class StubFilesystemLoader extends FilesystemLoader -{ - /** - * @return string|null - */ - protected function findTemplate($name, $throw = true) - { - // strip away bundle name - $parts = explode(':', $name); - - return parent::findTemplate(end($parts), $throw); - } -} diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php index 61be57e1a628d..b0696790bdcdc 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3HorizontalLayoutTest.php @@ -14,11 +14,11 @@ use Symfony\Bridge\Twig\Extension\FormExtension; use Symfony\Bridge\Twig\Extension\TranslationExtension; use Symfony\Bridge\Twig\Form\TwigRendererEngine; -use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubFilesystemLoader; use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator; use Symfony\Component\Form\FormRenderer; use Symfony\Component\Form\FormView; use Twig\Environment; +use Twig\Loader\FilesystemLoader; class FormExtensionBootstrap3HorizontalLayoutTest extends AbstractBootstrap3HorizontalLayoutTest { @@ -37,7 +37,7 @@ protected function setUp(): void { parent::setUp(); - $loader = new StubFilesystemLoader([ + $loader = new FilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', ]); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3LayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3LayoutTest.php index 9dcefcbee3e1e..237fb2fa99ef9 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3LayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap3LayoutTest.php @@ -14,11 +14,11 @@ use Symfony\Bridge\Twig\Extension\FormExtension; use Symfony\Bridge\Twig\Extension\TranslationExtension; use Symfony\Bridge\Twig\Form\TwigRendererEngine; -use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubFilesystemLoader; use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator; use Symfony\Component\Form\FormRenderer; use Symfony\Component\Form\FormView; use Twig\Environment; +use Twig\Loader\FilesystemLoader; class FormExtensionBootstrap3LayoutTest extends AbstractBootstrap3LayoutTest { @@ -33,7 +33,7 @@ protected function setUp(): void { parent::setUp(); - $loader = new StubFilesystemLoader([ + $loader = new FilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', ]); @@ -76,7 +76,7 @@ public function testStartTagHasActionAttributeWhenActionIsZero() public function testMoneyWidgetInIso() { - $environment = new Environment(new StubFilesystemLoader([ + $environment = new Environment(new FilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', ]), ['strict_variables' => true]); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4HorizontalLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4HorizontalLayoutTest.php index a7222867d1fc1..0d0933eb325f9 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4HorizontalLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4HorizontalLayoutTest.php @@ -14,11 +14,11 @@ use Symfony\Bridge\Twig\Extension\FormExtension; use Symfony\Bridge\Twig\Extension\TranslationExtension; use Symfony\Bridge\Twig\Form\TwigRendererEngine; -use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubFilesystemLoader; use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator; use Symfony\Component\Form\FormRenderer; use Symfony\Component\Form\FormView; use Twig\Environment; +use Twig\Loader\FilesystemLoader; /** * Class providing test cases for the Bootstrap 4 Twig form theme. @@ -39,7 +39,7 @@ protected function setUp(): void { parent::setUp(); - $loader = new StubFilesystemLoader([ + $loader = new FilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', ]); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4LayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4LayoutTest.php index ee13f62ceac2c..54b9b3e2a379f 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4LayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionBootstrap4LayoutTest.php @@ -14,11 +14,11 @@ use Symfony\Bridge\Twig\Extension\FormExtension; use Symfony\Bridge\Twig\Extension\TranslationExtension; use Symfony\Bridge\Twig\Form\TwigRendererEngine; -use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubFilesystemLoader; use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator; use Symfony\Component\Form\FormRenderer; use Symfony\Component\Form\FormView; use Twig\Environment; +use Twig\Loader\FilesystemLoader; /** * Class providing test cases for the Bootstrap 4 horizontal Twig form theme. @@ -37,7 +37,7 @@ protected function setUp(): void { parent::setUp(); - $loader = new StubFilesystemLoader([ + $loader = new FilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', ]); @@ -80,7 +80,7 @@ public function testStartTagHasActionAttributeWhenActionIsZero() public function testMoneyWidgetInIso() { - $environment = new Environment(new StubFilesystemLoader([ + $environment = new Environment(new FilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', ]), ['strict_variables' => true]); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php index 5ad451c0b8189..1c4b5f5febc96 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionDivLayoutTest.php @@ -14,13 +14,13 @@ use Symfony\Bridge\Twig\Extension\FormExtension; use Symfony\Bridge\Twig\Extension\TranslationExtension; use Symfony\Bridge\Twig\Form\TwigRendererEngine; -use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubFilesystemLoader; use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator; use Symfony\Component\Form\ChoiceList\View\ChoiceView; use Symfony\Component\Form\FormRenderer; use Symfony\Component\Form\FormView; use Symfony\Component\Form\Tests\AbstractDivLayoutTest; use Twig\Environment; +use Twig\Loader\FilesystemLoader; class FormExtensionDivLayoutTest extends AbstractDivLayoutTest { @@ -37,7 +37,7 @@ protected function setUp(): void { parent::setUp(); - $loader = new StubFilesystemLoader([ + $loader = new FilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', ]); @@ -169,7 +169,7 @@ public function testIsRootForm($expected, FormView $formView) public function testMoneyWidgetInIso() { - $environment = new Environment(new StubFilesystemLoader([ + $environment = new Environment(new FilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', ]), ['strict_variables' => true]); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php index 40d51c2bbbe9f..18528d64fb754 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/FormExtensionTableLayoutTest.php @@ -14,12 +14,12 @@ use Symfony\Bridge\Twig\Extension\FormExtension; use Symfony\Bridge\Twig\Extension\TranslationExtension; use Symfony\Bridge\Twig\Form\TwigRendererEngine; -use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubFilesystemLoader; use Symfony\Bridge\Twig\Tests\Extension\Fixtures\StubTranslator; use Symfony\Component\Form\FormRenderer; use Symfony\Component\Form\FormView; use Symfony\Component\Form\Tests\AbstractTableLayoutTest; use Twig\Environment; +use Twig\Loader\FilesystemLoader; class FormExtensionTableLayoutTest extends AbstractTableLayoutTest { @@ -36,7 +36,7 @@ protected function setUp(): void { parent::setUp(); - $loader = new StubFilesystemLoader([ + $loader = new FilesystemLoader([ __DIR__.'/../../Resources/views/Form', __DIR__.'/Fixtures/templates/form', ]); diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/HttpFoundationExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/HttpFoundationExtensionTest.php index 396f433bfda63..46031808589f9 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/HttpFoundationExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/HttpFoundationExtensionTest.php @@ -15,11 +15,9 @@ use Symfony\Bridge\Twig\Extension\HttpFoundationExtension; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\UrlHelper; use Symfony\Component\Routing\RequestContext; -/** - * @group legacy - */ class HttpFoundationExtensionTest extends TestCase { /** @@ -29,7 +27,7 @@ public function testGenerateAbsoluteUrl($expected, $path, $pathinfo) { $stack = new RequestStack(); $stack->push(Request::create($pathinfo)); - $extension = new HttpFoundationExtension($stack); + $extension = new HttpFoundationExtension(new UrlHelper($stack)); $this->assertEquals($expected, $extension->generateAbsoluteUrl($path)); } @@ -67,7 +65,7 @@ public function testGenerateAbsoluteUrlWithRequestContext($path, $baseUrl, $host } $requestContext = new RequestContext($baseUrl, 'GET', $host, $scheme, $httpPort, $httpsPort, $path); - $extension = new HttpFoundationExtension(new RequestStack(), $requestContext); + $extension = new HttpFoundationExtension(new UrlHelper(new RequestStack(), $requestContext)); $this->assertEquals($expected, $extension->generateAbsoluteUrl($path)); } @@ -81,7 +79,7 @@ public function testGenerateAbsoluteUrlWithoutRequestAndRequestContext($path) $this->markTestSkipped('The Routing component is needed to run tests that depend on its request context.'); } - $extension = new HttpFoundationExtension(new RequestStack()); + $extension = new HttpFoundationExtension(new UrlHelper(new RequestStack())); $this->assertEquals($path, $extension->generateAbsoluteUrl($path)); } @@ -107,7 +105,7 @@ public function testGenerateAbsoluteUrlWithScriptFileName() $stack = new RequestStack(); $stack->push($request); - $extension = new HttpFoundationExtension($stack); + $extension = new HttpFoundationExtension(new UrlHelper($stack)); $this->assertEquals( 'http://localhost/app/web/bundles/framework/css/structure.css', @@ -126,7 +124,7 @@ public function testGenerateRelativePath($expected, $path, $pathinfo) $stack = new RequestStack(); $stack->push(Request::create($pathinfo)); - $extension = new HttpFoundationExtension($stack); + $extension = new HttpFoundationExtension(new UrlHelper($stack)); $this->assertEquals($expected, $extension->generateRelativePath($path)); } diff --git a/src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php b/src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php index d082e9b5de639..f384fa59c5d7b 100644 --- a/src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Extension/TranslationExtensionTest.php @@ -47,15 +47,6 @@ public function testTrans($template, $expected, array $variables = []) $this->assertEquals($expected, $this->getTemplate($template)->render($variables)); } - /** - * @group legacy - * @dataProvider getTransChoiceTests - */ - public function testTransChoice($template, $expected, array $variables = []) - { - $this->testTrans($template, $expected, $variables); - } - public function testTransUnknownKeyword() { $this->expectException('Twig\Error\SyntaxError'); @@ -70,16 +61,6 @@ public function testTransComplexBody() $this->getTemplate("{% trans %}\n{{ 1 + 2 }}{% endtrans %}")->render(); } - /** - * @group legacy - */ - public function testTransChoiceComplexBody() - { - $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() { return [ @@ -140,69 +121,6 @@ public function getTransTests() ]; } - /** - * @group legacy - */ - public function getTransChoiceTests() - { - return [ - // trans tag - ['{% trans %}Hello{% endtrans %}', 'Hello'], - ['{% trans %}%name%{% endtrans %}', 'Symfony', ['name' => 'Symfony']], - - ['{% trans from elsewhere %}Hello{% endtrans %}', 'Hello'], - - ['{% trans %}Hello %name%{% endtrans %}', 'Hello Symfony', ['name' => 'Symfony']], - ['{% trans with { \'%name%\': \'Symfony\' } %}Hello %name%{% endtrans %}', 'Hello Symfony'], - ['{% set vars = { \'%name%\': \'Symfony\' } %}{% trans with vars %}Hello %name%{% endtrans %}', 'Hello Symfony'], - - ['{% trans into "fr"%}Hello{% endtrans %}', 'Hello'], - - // transchoice - [ - '{% transchoice count from "messages" %}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples{% endtranschoice %}', - 'There is no apples', - ['count' => 0], - ], - [ - '{% transchoice count %}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples{% endtranschoice %}', - 'There is 5 apples', - ['count' => 5], - ], - [ - '{% transchoice count %}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%){% endtranschoice %}', - 'There is 5 apples (Symfony)', - ['count' => 5, 'name' => 'Symfony'], - ], - [ - '{% transchoice count with { \'%name%\': \'Symfony\' } %}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%){% endtranschoice %}', - 'There is 5 apples (Symfony)', - ['count' => 5], - ], - [ - '{% transchoice count into "fr"%}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples{% endtranschoice %}', - 'There is no apples', - ['count' => 0], - ], - [ - '{% transchoice 5 into "fr"%}{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples{% endtranschoice %}', - 'There is 5 apples', - ], - - // trans filter - ['{{ "Hello"|trans }}', 'Hello'], - ['{{ name|trans }}', 'Symfony', ['name' => 'Symfony']], - ['{{ hello|trans({ \'%name%\': \'Symfony\' }) }}', 'Hello Symfony', ['hello' => 'Hello %name%']], - ['{% set vars = { \'%name%\': \'Symfony\' } %}{{ hello|trans(vars) }}', 'Hello Symfony', ['hello' => 'Hello %name%']], - ['{{ "Hello"|trans({}, "messages", "fr") }}', 'Hello'], - - // transchoice filter - ['{{ "{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples"|transchoice(count) }}', 'There is 5 apples', ['count' => 5]], - ['{{ text|transchoice(5, {\'%name%\': \'Symfony\'}) }}', 'There is 5 apples (Symfony)', ['text' => '{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples (%name%)']], - ['{{ "{0} There is no apples|{1} There is one apple|]1,Inf] There is %count% apples"|transchoice(count, {}, "messages", "fr") }}', 'There is 5 apples', ['count' => 5]], - ]; - } - public function testDefaultTranslationDomain() { $templates = [ diff --git a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.php b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.php index 5abfe1e92a6ca..16fde044bae6d 100644 --- a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.php +++ b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationDefaultDomainNodeVisitorTest.php @@ -79,15 +79,11 @@ public function getDefaultDomainAssignmentTestData() { return [ [TwigNodeProvider::getTransFilter(self::$message)], - [TwigNodeProvider::getTransChoiceFilter(self::$message)], [TwigNodeProvider::getTransTag(self::$message)], // with named arguments [TwigNodeProvider::getTransFilter(self::$message, null, [ 'arguments' => new ArrayExpression([], 0), ])], - [TwigNodeProvider::getTransChoiceFilter(self::$message), null, [ - 'arguments' => new ArrayExpression([], 0), - ]], ]; } } diff --git a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.php b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.php index 11d16e4cd6744..a2cd6963d8f3d 100644 --- a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.php +++ b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TranslationNodeVisitorTest.php @@ -57,10 +57,8 @@ public function getMessagesExtractionTestData() return [ [TwigNodeProvider::getTransFilter($message), [[$message, null]]], - [TwigNodeProvider::getTransChoiceFilter($message), [[$message, null]]], [TwigNodeProvider::getTransTag($message), [[$message, null]]], [TwigNodeProvider::getTransFilter($message, $domain), [[$message, $domain]]], - [TwigNodeProvider::getTransChoiceFilter($message, $domain), [[$message, $domain]]], [TwigNodeProvider::getTransTag($message, $domain), [[$message, $domain]]], ]; } diff --git a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TwigNodeProvider.php b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TwigNodeProvider.php index 5147724675817..69311afdc824d 100644 --- a/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TwigNodeProvider.php +++ b/src/Symfony/Bridge/Twig/Tests/NodeVisitor/TwigNodeProvider.php @@ -53,24 +53,6 @@ public static function getTransFilter($message, $domain = null, $arguments = nul ); } - public static function getTransChoiceFilter($message, $domain = null, $arguments = null) - { - if (!$arguments) { - $arguments = $domain ? [ - new ConstantExpression(0, 0), - new ArrayExpression([], 0), - new ConstantExpression($domain, 0), - ] : []; - } - - return new FilterExpression( - new ConstantExpression($message, 0), - new ConstantExpression('transchoice', 0), - new Node($arguments), - 0 - ); - } - public static function getTransTag($message, $domain = null) { return new TransNode( diff --git a/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php b/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php index 225d80662a3dd..3f497202b4ed5 100644 --- a/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php +++ b/src/Symfony/Bridge/Twig/Tests/Translation/TwigExtractorTest.php @@ -50,15 +50,6 @@ public function testExtract($template, $messages) } } - /** - * @group legacy - * @dataProvider getLegacyExtractData - */ - public function testLegacyExtract($template, $messages) - { - $this->testExtract($template, $messages); - } - public function getExtractData() { return [ @@ -80,24 +71,6 @@ public function getExtractData() ]; } - /** - * @group legacy - */ - public function getLegacyExtractData() - { - return [ - ['{{ "new key" | transchoice(1) }}', ['new key' => 'messages']], - ['{{ "new key" | transchoice(1) | upper }}', ['new key' => 'messages']], - ['{{ "new key" | transchoice(1, {}, "domain") }}', ['new key' => 'domain']], - - // make sure 'trans_default_domain' tag is supported - ['{% trans_default_domain "domain" %}{{ "new key"|transchoice }}', ['new key' => 'domain']], - - // make sure this works with twig's named arguments - ['{{ "new key" | transchoice(domain="domain", count=1) }}', ['new key' => 'domain']], - ]; - } - /** * @dataProvider resourcesWithSyntaxErrorsProvider */ diff --git a/src/Symfony/Bridge/Twig/Tests/TwigEngineTest.php b/src/Symfony/Bridge/Twig/Tests/TwigEngineTest.php deleted file mode 100644 index f7a7461931914..0000000000000 --- a/src/Symfony/Bridge/Twig/Tests/TwigEngineTest.php +++ /dev/null @@ -1,82 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bridge\Twig\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Bridge\Twig\TwigEngine; -use Symfony\Component\Templating\TemplateReference; -use Twig\Environment; -use Twig\Loader\ArrayLoader; - -/** - * @group legacy - */ -class TwigEngineTest extends TestCase -{ - public function testExistsWithTemplateInstances() - { - $engine = $this->getTwig(); - - $this->assertTrue($engine->exists($this->getMockForAbstractClass('Twig\Template', [], '', false))); - } - - public function testExistsWithNonExistentTemplates() - { - $engine = $this->getTwig(); - - $this->assertFalse($engine->exists('foobar')); - $this->assertFalse($engine->exists(new TemplateReference('foorbar'))); - } - - public function testExistsWithTemplateWithSyntaxErrors() - { - $engine = $this->getTwig(); - - $this->assertTrue($engine->exists('error')); - $this->assertTrue($engine->exists(new TemplateReference('error'))); - } - - public function testExists() - { - $engine = $this->getTwig(); - - $this->assertTrue($engine->exists('index')); - $this->assertTrue($engine->exists(new TemplateReference('index'))); - } - - public function testRender() - { - $engine = $this->getTwig(); - - $this->assertSame('foo', $engine->render('index')); - $this->assertSame('foo', $engine->render(new TemplateReference('index'))); - } - - public function testRenderWithError() - { - $this->expectException('Twig\Error\SyntaxError'); - $engine = $this->getTwig(); - - $engine->render(new TemplateReference('error')); - } - - protected function getTwig() - { - $twig = new Environment(new ArrayLoader([ - 'index' => 'foo', - 'error' => '{{ foo }', - ])); - $parser = $this->getMockBuilder('Symfony\Component\Templating\TemplateNameParserInterface')->getMock(); - - return new TwigEngine($twig, $parser); - } -} diff --git a/src/Symfony/Bridge/Twig/TokenParser/DumpTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/DumpTokenParser.php index c13297f23258d..341dc41855ab0 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/DumpTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/DumpTokenParser.php @@ -26,17 +26,13 @@ * {% dump foo, bar %} * * @author Julien Galenski - * - * @final since Symfony 4.4 */ -class DumpTokenParser extends AbstractTokenParser +final class DumpTokenParser extends AbstractTokenParser { /** * {@inheritdoc} - * - * @return Node */ - public function parse(Token $token) + public function parse(Token $token): Node { $values = null; if (!$this->parser->getStream()->test(Token::BLOCK_END_TYPE)) { @@ -49,10 +45,8 @@ public function parse(Token $token) /** * {@inheritdoc} - * - * @return string */ - public function getTag() + public function getTag(): string { return 'dump'; } diff --git a/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php index 58fe3dd6be261..ef5dacb59ddd1 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/FormThemeTokenParser.php @@ -21,17 +21,13 @@ * Token Parser for the 'form_theme' tag. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class FormThemeTokenParser extends AbstractTokenParser +final class FormThemeTokenParser extends AbstractTokenParser { /** - * Parses a token and returns a node. - * - * @return Node + * {@inheritdoc} */ - public function parse(Token $token) + public function parse(Token $token): Node { $lineno = $token->getLine(); $stream = $this->parser->getStream(); @@ -59,11 +55,9 @@ public function parse(Token $token) } /** - * Gets the tag name associated with this token parser. - * - * @return string The tag name + * {@inheritdoc} */ - public function getTag() + public function getTag(): string { return 'form_theme'; } diff --git a/src/Symfony/Bridge/Twig/TokenParser/StopwatchTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/StopwatchTokenParser.php index e1ac39cf8f390..a70e94b801b65 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/StopwatchTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/StopwatchTokenParser.php @@ -21,10 +21,8 @@ * Token Parser for the stopwatch tag. * * @author Wouter J - * - * @final since Symfony 4.4 */ -class StopwatchTokenParser extends AbstractTokenParser +final class StopwatchTokenParser extends AbstractTokenParser { protected $stopwatchIsAvailable; @@ -33,10 +31,7 @@ public function __construct(bool $stopwatchIsAvailable) $this->stopwatchIsAvailable = $stopwatchIsAvailable; } - /** - * @return Node - */ - public function parse(Token $token) + public function parse(Token $token): Node { $lineno = $token->getLine(); $stream = $this->parser->getStream(); @@ -57,15 +52,12 @@ public function parse(Token $token) return $body; } - public function decideStopwatchEnd(Token $token) + public function decideStopwatchEnd(Token $token): bool { return $token->test('endstopwatch'); } - /** - * @return string - */ - public function getTag() + public function getTag(): string { return 'stopwatch'; } diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php deleted file mode 100644 index 036dae752af59..0000000000000 --- a/src/Symfony/Bridge/Twig/TokenParser/TransChoiceTokenParser.php +++ /dev/null @@ -1,98 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bridge\Twig\TokenParser; - -use Symfony\Bridge\Twig\Node\TransNode; -use Twig\Error\SyntaxError; -use Twig\Node\Expression\AbstractExpression; -use Twig\Node\Expression\ArrayExpression; -use Twig\Node\Node; -use Twig\Node\TextNode; -use Twig\Token; -use Twig\TokenParser\AbstractTokenParser; - -/** - * Token Parser for the 'transchoice' tag. - * - * @author Fabien Potencier - * - * @deprecated since Symfony 4.2, use the "trans" tag with a "%count%" parameter instead - * - * @final since Symfony 4.4 - */ -class TransChoiceTokenParser extends AbstractTokenParser -{ - /** - * {@inheritdoc} - * - * @return Node - */ - public function parse(Token $token) - { - $lineno = $token->getLine(); - $stream = $this->parser->getStream(); - - @trigger_error(sprintf('The "transchoice" tag is deprecated since Symfony 4.2, use the "trans" one instead with a "%%count%%" parameter in %s line %d.', $stream->getSourceContext()->getName(), $lineno), E_USER_DEPRECATED); - - $vars = new ArrayExpression([], $lineno); - - $count = $this->parser->getExpressionParser()->parseExpression(); - - $domain = null; - $locale = null; - - if ($stream->test('with')) { - // {% transchoice count with vars %} - $stream->next(); - $vars = $this->parser->getExpressionParser()->parseExpression(); - } - - if ($stream->test('from')) { - // {% transchoice count from "messages" %} - $stream->next(); - $domain = $this->parser->getExpressionParser()->parseExpression(); - } - - if ($stream->test('into')) { - // {% transchoice count into "fr" %} - $stream->next(); - $locale = $this->parser->getExpressionParser()->parseExpression(); - } - - $stream->expect(Token::BLOCK_END_TYPE); - - $body = $this->parser->subparse([$this, 'decideTransChoiceFork'], true); - - if (!$body instanceof TextNode && !$body instanceof AbstractExpression) { - throw new SyntaxError('A message inside a transchoice tag must be a simple text.', $body->getTemplateLine(), $stream->getSourceContext()); - } - - $stream->expect(Token::BLOCK_END_TYPE); - - return new TransNode($body, $domain, $count, $vars, $locale, $lineno, $this->getTag()); - } - - public function decideTransChoiceFork($token) - { - return $token->test(['endtranschoice']); - } - - /** - * {@inheritdoc} - * - * @return string - */ - public function getTag() - { - return 'transchoice'; - } -} diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransDefaultDomainTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransDefaultDomainTokenParser.php index e6b16680f7b7c..19b820497d9fa 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/TransDefaultDomainTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/TransDefaultDomainTokenParser.php @@ -20,17 +20,13 @@ * Token Parser for the 'trans_default_domain' tag. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class TransDefaultDomainTokenParser extends AbstractTokenParser +final class TransDefaultDomainTokenParser extends AbstractTokenParser { /** * {@inheritdoc} - * - * @return Node */ - public function parse(Token $token) + public function parse(Token $token): Node { $expr = $this->parser->getExpressionParser()->parseExpression(); @@ -41,10 +37,8 @@ public function parse(Token $token) /** * {@inheritdoc} - * - * @return string */ - public function getTag() + public function getTag(): string { return 'trans_default_domain'; } diff --git a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php index e72240b6e8119..ffe8828590852 100644 --- a/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php +++ b/src/Symfony/Bridge/Twig/TokenParser/TransTokenParser.php @@ -24,17 +24,13 @@ * Token Parser for the 'trans' tag. * * @author Fabien Potencier - * - * @final since Symfony 4.4 */ -class TransTokenParser extends AbstractTokenParser +final class TransTokenParser extends AbstractTokenParser { /** * {@inheritdoc} - * - * @return Node */ - public function parse(Token $token) + public function parse(Token $token): Node { $lineno = $token->getLine(); $stream = $this->parser->getStream(); @@ -84,17 +80,15 @@ public function parse(Token $token) return new TransNode($body, $domain, $count, $vars, $locale, $lineno, $this->getTag()); } - public function decideTransFork($token) + public function decideTransFork(Token $token): bool { return $token->test(['endtrans']); } /** * {@inheritdoc} - * - * @return string */ - public function getTag() + public function getTag(): string { return 'trans'; } diff --git a/src/Symfony/Bridge/Twig/Translation/TwigExtractor.php b/src/Symfony/Bridge/Twig/Translation/TwigExtractor.php index b7c787226656f..b75ba559b7d16 100644 --- a/src/Symfony/Bridge/Twig/Translation/TwigExtractor.php +++ b/src/Symfony/Bridge/Twig/Translation/TwigExtractor.php @@ -72,12 +72,12 @@ public function extract($resource, MessageCatalogue $catalogue) /** * {@inheritdoc} */ - public function setPrefix($prefix) + public function setPrefix(string $prefix) { $this->prefix = $prefix; } - protected function extractTemplate($template, MessageCatalogue $catalogue) + protected function extractTemplate(string $template, MessageCatalogue $catalogue) { $visitor = $this->twig->getExtension('Symfony\Bridge\Twig\Extension\TranslationExtension')->getTranslationNodeVisitor(); $visitor->enable(); @@ -92,11 +92,9 @@ protected function extractTemplate($template, MessageCatalogue $catalogue) } /** - * @param string $file - * * @return bool */ - protected function canBeExtracted($file) + protected function canBeExtracted(string $file) { return $this->isFile($file) && 'twig' === pathinfo($file, PATHINFO_EXTENSION); } diff --git a/src/Symfony/Bridge/Twig/TwigEngine.php b/src/Symfony/Bridge/Twig/TwigEngine.php deleted file mode 100644 index 61e90d4b30915..0000000000000 --- a/src/Symfony/Bridge/Twig/TwigEngine.php +++ /dev/null @@ -1,140 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bridge\Twig; - -@trigger_error('The '.TwigEngine::class.' class is deprecated since version 4.3 and will be removed in 5.0; use \Twig\Environment instead.', E_USER_DEPRECATED); - -use Symfony\Component\Templating\EngineInterface; -use Symfony\Component\Templating\StreamingEngineInterface; -use Symfony\Component\Templating\TemplateNameParserInterface; -use Symfony\Component\Templating\TemplateReferenceInterface; -use Twig\Environment; -use Twig\Error\Error; -use Twig\Error\LoaderError; -use Twig\Loader\ExistsLoaderInterface; -use Twig\Loader\SourceContextLoaderInterface; -use Twig\Template; - -/** - * This engine knows how to render Twig templates. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class TwigEngine implements EngineInterface, StreamingEngineInterface -{ - protected $environment; - protected $parser; - - public function __construct(Environment $environment, TemplateNameParserInterface $parser) - { - $this->environment = $environment; - $this->parser = $parser; - } - - /** - * {@inheritdoc} - * - * It also supports Template as name parameter. - * - * @throws Error if something went wrong like a thrown exception while rendering the template - */ - public function render($name, array $parameters = []) - { - return $this->load($name)->render($parameters); - } - - /** - * {@inheritdoc} - * - * It also supports Template as name parameter. - * - * @throws Error if something went wrong like a thrown exception while rendering the template - */ - public function stream($name, array $parameters = []) - { - $this->load($name)->display($parameters); - } - - /** - * {@inheritdoc} - * - * It also supports Template as name parameter. - */ - public function exists($name) - { - if ($name instanceof Template) { - return true; - } - - $loader = $this->environment->getLoader(); - - 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) { - } - - return false; - } - - return $loader->exists((string) $name); - } - - /** - * {@inheritdoc} - * - * It also supports Template as name parameter. - */ - public function supports($name) - { - if ($name instanceof Template) { - return true; - } - - $template = $this->parser->parse($name); - - return 'twig' === $template->get('engine'); - } - - /** - * Loads the given template. - * - * @param string|TemplateReferenceInterface|Template $name A template name or an instance of - * TemplateReferenceInterface or Template - * - * @return Template - * - * @throws \InvalidArgumentException if the template does not exist - */ - protected function load($name) - { - if ($name instanceof Template) { - return $name; - } - - try { - return $this->environment->load((string) $name)->unwrap(); - } catch (LoaderError $e) { - throw new \InvalidArgumentException($e->getMessage(), $e->getCode(), $e); - } - } -} diff --git a/src/Symfony/Bridge/Twig/composer.json b/src/Symfony/Bridge/Twig/composer.json index d8f06f87bd133..a2700555f0d33 100644 --- a/src/Symfony/Bridge/Twig/composer.json +++ b/src/Symfony/Bridge/Twig/composer.json @@ -16,44 +16,43 @@ } ], "require": { - "php": "^7.1.3", + "php": "^7.2.5", "symfony/translation-contracts": "^1.1|^2", - "twig/twig": "^1.41|^2.10|^3.0" + "twig/twig": "^2.10|^3.0" }, "require-dev": { "egulias/email-validator": "^2.1.10", - "symfony/asset": "^3.4|^4.0|^5.0", - "symfony/dependency-injection": "^3.4|^4.0|^5.0", - "symfony/error-handler": "^4.4|^5.0", - "symfony/finder": "^3.4|^4.0|^5.0", - "symfony/form": "^4.4|^5.0", - "symfony/http-foundation": "^4.3|^5.0", - "symfony/http-kernel": "^4.4", - "symfony/mime": "^4.3|^5.0", + "symfony/asset": "^4.4|^5.0", + "symfony/dependency-injection": "^4.4|^5.0", + "symfony/finder": "^4.4|^5.0", + "symfony/form": "^5.0", + "symfony/http-foundation": "^4.4|^5.0", + "symfony/http-kernel": "^4.4|^5.0", + "symfony/mime": "^4.4|^5.0", "symfony/polyfill-intl-icu": "~1.0", - "symfony/routing": "^3.4|^4.0|^5.0", - "symfony/templating": "^3.4|^4.0|^5.0", - "symfony/translation": "^4.2.1|^5.0", - "symfony/yaml": "^3.4|^4.0|^5.0", + "symfony/routing": "^4.4|^5.0", + "symfony/translation": "^5.0", + "symfony/yaml": "^4.4|^5.0", "symfony/security-acl": "^2.8|^3.0", - "symfony/security-core": "^3.0|^4.0|^5.0", - "symfony/security-csrf": "^3.4|^4.0|^5.0", - "symfony/security-http": "^3.4|^4.0|^5.0", - "symfony/stopwatch": "^3.4|^4.0|^5.0", - "symfony/console": "^3.4|^4.0|^5.0", - "symfony/expression-language": "^3.4|^4.0|^5.0", + "symfony/security-core": "^4.4|^5.0", + "symfony/security-csrf": "^4.4|^5.0", + "symfony/security-http": "^4.4|^5.0", + "symfony/stopwatch": "^4.4|^5.0", + "symfony/console": "^4.4|^5.0", + "symfony/expression-language": "^4.4|^5.0", "symfony/web-link": "^4.4|^5.0", - "symfony/workflow": "^4.3|^5.0", + "symfony/workflow": "^4.4|^5.0", "twig/cssinliner-extra": "^2.12", "twig/inky-extra": "^2.12", "twig/markdown-extra": "^2.12" }, "conflict": { - "symfony/console": "<3.4", - "symfony/form": "<4.4", - "symfony/http-foundation": "<4.3", - "symfony/translation": "<4.2", - "symfony/workflow": "<4.3" + "symfony/console": "<4.4", + "symfony/form": "<5.0", + "symfony/http-foundation": "<4.4", + "symfony/http-kernel": "<4.4", + "symfony/translation": "<5.0", + "symfony/workflow": "<4.4" }, "suggest": { "symfony/finder": "", @@ -61,7 +60,6 @@ "symfony/form": "For using the FormExtension", "symfony/http-kernel": "For using the HttpKernelExtension", "symfony/routing": "For using the RoutingExtension", - "symfony/templating": "For using the TwigEngine", "symfony/translation": "For using the TranslationExtension", "symfony/yaml": "For using the YamlExtension", "symfony/security-core": "For using the SecurityExtension", @@ -81,7 +79,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.1-dev" } } } diff --git a/src/Symfony/Bundle/DebugBundle/composer.json b/src/Symfony/Bundle/DebugBundle/composer.json index 5087c97e08b26..ae24f964262d6 100644 --- a/src/Symfony/Bundle/DebugBundle/composer.json +++ b/src/Symfony/Bundle/DebugBundle/composer.json @@ -16,20 +16,20 @@ } ], "require": { - "php": "^7.1.3", + "php": "^7.2.5", "ext-xml": "*", - "symfony/http-kernel": "^3.4|^4.0|^5.0", - "symfony/twig-bridge": "^3.4|^4.0|^5.0", - "symfony/var-dumper": "^4.1.1|^5.0" + "symfony/http-kernel": "^4.4|^5.0", + "symfony/twig-bridge": "^4.4|^5.0", + "symfony/var-dumper": "^4.4|^5.0" }, "require-dev": { - "symfony/config": "^4.2|^5.0", - "symfony/dependency-injection": "^3.4|^4.0|^5.0", - "symfony/web-profiler-bundle": "^3.4|^4.0|^5.0" + "symfony/config": "^4.4|^5.0", + "symfony/dependency-injection": "^4.4|^5.0", + "symfony/web-profiler-bundle": "^4.4|^5.0" }, "conflict": { - "symfony/config": "<4.2", - "symfony/dependency-injection": "<3.4" + "symfony/config": "<4.4", + "symfony/dependency-injection": "<4.4" }, "suggest": { "symfony/config": "For service container configuration", @@ -44,7 +44,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.1-dev" } } } diff --git a/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md b/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md index 0220844b2697d..dfc47d7b99bee 100644 --- a/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md +++ b/src/Symfony/Bundle/FrameworkBundle/CHANGELOG.md @@ -1,6 +1,33 @@ CHANGELOG ========= +5.1.0 +----- + + * Marked `MicroKernelTrait::configureRoutes()` as `@internal` and `@final`. + * Deprecated not overriding `MicroKernelTrait::configureRouting()`. + +5.0.0 +----- + + * Removed support to load translation resources from the legacy directories `src/Resources/translations/` and `src/Resources//translations/` + * Removed `ControllerNameParser`. + * Removed `ResolveControllerNameSubscriber` + * Removed support for `bundle:controller:action` to reference controllers. Use `serviceOrFqcn::method` instead + * Removed support for PHP templating, use Twig instead + * Removed `Controller`, use `AbstractController` instead + * Removed `Client`, use `KernelBrowser` instead + * Removed `ContainerAwareCommand`, use dependency injection instead + * Removed the `validation.strict_email` option, use `validation.email_validation_mode` instead + * Removed the `cache.app.simple` service and its corresponding PSR-16 autowiring alias + * Removed cache-related compiler passes and `RequestDataCollector` + * Removed the `translator.selector` and `session.save_listener` services + * Removed `SecurityUserValueResolver`, use `UserValueResolver` instead + * Removed `routing.loader.service`. + * Service route loaders must be tagged with `routing.route_loader`. + * Added `slugger` service and `SluggerInterface` alias + * Removed the `lock.store.flock`, `lock.store.semaphore`, `lock.store.memcached.abstract` and `lock.store.redis.abstract` services. + 4.4.0 ----- diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AbstractPhpFileCacheWarmer.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AbstractPhpFileCacheWarmer.php index a626ff8b0fd27..0e4561ad4754b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AbstractPhpFileCacheWarmer.php +++ b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AbstractPhpFileCacheWarmer.php @@ -43,7 +43,7 @@ public function isOptional() /** * {@inheritdoc} */ - public function warmUp($cacheDir) + public function warmUp(string $cacheDir) { $arrayAdapter = new ArrayAdapter(); @@ -81,9 +81,7 @@ final protected function ignoreAutoloadException(string $class, \Exception $exce } /** - * @param string $cacheDir - * * @return bool false if there is nothing to warm-up */ - abstract protected function doWarmUp($cacheDir, ArrayAdapter $arrayAdapter); + abstract protected function doWarmUp(string $cacheDir, ArrayAdapter $arrayAdapter); } diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AnnotationsCacheWarmer.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AnnotationsCacheWarmer.php index 78c118a99912a..2169eecf8a626 100644 --- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AnnotationsCacheWarmer.php +++ b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/AnnotationsCacheWarmer.php @@ -14,7 +14,6 @@ use Doctrine\Common\Annotations\AnnotationException; use Doctrine\Common\Annotations\CachedReader; use Doctrine\Common\Annotations\Reader; -use Psr\Cache\CacheItemPoolInterface; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\DoctrineProvider; @@ -31,17 +30,10 @@ class AnnotationsCacheWarmer extends AbstractPhpFileCacheWarmer private $debug; /** - * @param string $phpArrayFile The PHP file where annotations are cached - * @param string $excludeRegexp - * @param bool $debug + * @param string $phpArrayFile The PHP file where annotations are cached */ - public function __construct(Reader $annotationReader, string $phpArrayFile, $excludeRegexp = null, $debug = false) + public function __construct(Reader $annotationReader, string $phpArrayFile, string $excludeRegexp = null, bool $debug = false) { - if ($excludeRegexp instanceof CacheItemPoolInterface) { - @trigger_error(sprintf('The CacheItemPoolInterface $fallbackPool argument of "%s()" is deprecated since Symfony 4.2, you should not pass it anymore.', __METHOD__), E_USER_DEPRECATED); - $excludeRegexp = $debug; - $debug = 4 < \func_num_args() && func_get_arg(4); - } parent::__construct($phpArrayFile); $this->annotationReader = $annotationReader; $this->excludeRegexp = $excludeRegexp; @@ -51,7 +43,7 @@ public function __construct(Reader $annotationReader, string $phpArrayFile, $exc /** * {@inheritdoc} */ - protected function doWarmUp($cacheDir, ArrayAdapter $arrayAdapter) + protected function doWarmUp(string $cacheDir, ArrayAdapter $arrayAdapter) { $annotatedClassPatterns = $cacheDir.'/annotations.map'; diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/RouterCacheWarmer.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/RouterCacheWarmer.php index 61d9f21a5aaf5..fecce2759f7a4 100644 --- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/RouterCacheWarmer.php +++ b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/RouterCacheWarmer.php @@ -12,10 +12,10 @@ namespace Symfony\Bundle\FrameworkBundle\CacheWarmer; use Psr\Container\ContainerInterface; -use Symfony\Bundle\FrameworkBundle\DependencyInjection\CompatibilityServiceSubscriberInterface as ServiceSubscriberInterface; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; use Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface; use Symfony\Component\Routing\RouterInterface; +use Symfony\Contracts\Service\ServiceSubscriberInterface; /** * Generates the router matcher and generator classes. @@ -35,11 +35,9 @@ public function __construct(ContainerInterface $container) } /** - * Warms up the cache. - * - * @param string $cacheDir The cache directory + * {@inheritdoc} */ - public function warmUp($cacheDir) + public function warmUp(string $cacheDir) { $router = $this->container->get('router'); @@ -49,7 +47,7 @@ public function warmUp($cacheDir) return; } - @trigger_error(sprintf('Passing a %s without implementing %s is deprecated since Symfony 4.1.', RouterInterface::class, WarmableInterface::class), \E_USER_DEPRECATED); + throw new \LogicException(sprintf('The router %s cannot be warmed up because it does not implement %s.', \get_class($router), WarmableInterface::class)); } /** diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/SerializerCacheWarmer.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/SerializerCacheWarmer.php index ee38623c552cc..0ada0ffc94349 100644 --- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/SerializerCacheWarmer.php +++ b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/SerializerCacheWarmer.php @@ -12,7 +12,6 @@ namespace Symfony\Bundle\FrameworkBundle\CacheWarmer; use Doctrine\Common\Annotations\AnnotationException; -use Psr\Cache\CacheItemPoolInterface; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Serializer\Mapping\Factory\CacheClassMetadataFactory; use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory; @@ -36,9 +35,6 @@ class SerializerCacheWarmer extends AbstractPhpFileCacheWarmer */ public function __construct(array $loaders, string $phpArrayFile) { - if (2 < \func_num_args() && func_get_arg(2) instanceof CacheItemPoolInterface) { - @trigger_error(sprintf('The CacheItemPoolInterface $fallbackPool argument of "%s()" is deprecated since Symfony 4.2, you should not pass it anymore.', __METHOD__), E_USER_DEPRECATED); - } parent::__construct($phpArrayFile); $this->loaders = $loaders; } @@ -46,7 +42,7 @@ public function __construct(array $loaders, string $phpArrayFile) /** * {@inheritdoc} */ - protected function doWarmUp($cacheDir, ArrayAdapter $arrayAdapter) + protected function doWarmUp(string $cacheDir, ArrayAdapter $arrayAdapter) { if (!class_exists(CacheClassMetadataFactory::class) || !method_exists(XmlFileLoader::class, 'getMappedClasses') || !method_exists(YamlFileLoader::class, 'getMappedClasses')) { return false; diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplateFinder.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplateFinder.php deleted file mode 100644 index f49e856c81aab..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplateFinder.php +++ /dev/null @@ -1,111 +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\CacheWarmer; - -@trigger_error('The '.TemplateFinder::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\Finder\Finder; -use Symfony\Component\HttpKernel\Bundle\BundleInterface; -use Symfony\Component\HttpKernel\KernelInterface; -use Symfony\Component\Templating\TemplateNameParserInterface; -use Symfony\Component\Templating\TemplateReferenceInterface; - -/** - * Finds all the templates. - * - * @author Victor Berchet - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class TemplateFinder implements TemplateFinderInterface -{ - private $kernel; - private $parser; - private $rootDir; - private $templates; - - /** - * @param string $rootDir The directory where global templates can be stored - */ - public function __construct(KernelInterface $kernel, TemplateNameParserInterface $parser, string $rootDir) - { - $this->kernel = $kernel; - $this->parser = $parser; - $this->rootDir = $rootDir; - } - - /** - * Find all the templates in the bundle and in the kernel Resources folder. - * - * @return TemplateReferenceInterface[] - */ - public function findAllTemplates() - { - if (null !== $this->templates) { - return $this->templates; - } - - $templates = []; - - foreach ($this->kernel->getBundles() as $bundle) { - $templates = array_merge($templates, $this->findTemplatesInBundle($bundle)); - } - - $templates = array_merge($templates, $this->findTemplatesInFolder($this->rootDir.'/views')); - - return $this->templates = $templates; - } - - /** - * Find templates in the given directory. - * - * @return TemplateReferenceInterface[] - */ - private function findTemplatesInFolder(string $dir): array - { - $templates = []; - - if (is_dir($dir)) { - $finder = new Finder(); - foreach ($finder->files()->followLinks()->in($dir) as $file) { - $template = $this->parser->parse($file->getRelativePathname()); - if (false !== $template) { - $templates[] = $template; - } - } - } - - return $templates; - } - - /** - * Find templates in the given bundle. - * - * @param BundleInterface $bundle The bundle where to look for templates - * - * @return TemplateReferenceInterface[] - */ - private function findTemplatesInBundle(BundleInterface $bundle): array - { - $name = $bundle->getName(); - $templates = array_unique(array_merge( - $this->findTemplatesInFolder($bundle->getPath().'/Resources/views'), - $this->findTemplatesInFolder($this->rootDir.'/'.$name.'/views') - )); - - foreach ($templates as $i => $template) { - $templates[$i] = $template->set('bundle', $name); - } - - return $templates; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplateFinderInterface.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplateFinderInterface.php deleted file mode 100644 index f5ed025facfdb..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplateFinderInterface.php +++ /dev/null @@ -1,31 +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\CacheWarmer; - -@trigger_error('The '.TemplateFinderInterface::class.' interface is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -/** - * Interface for finding all the templates. - * - * @author Victor Berchet - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -interface TemplateFinderInterface -{ - /** - * Find all the templates. - * - * @return array An array of templates of type TemplateReferenceInterface - */ - public function findAllTemplates(); -} diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplatePathsCacheWarmer.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplatePathsCacheWarmer.php deleted file mode 100644 index 9db00d828b64e..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/TemplatePathsCacheWarmer.php +++ /dev/null @@ -1,66 +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\CacheWarmer; - -@trigger_error('The '.TemplatePathsCacheWarmer::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator; -use Symfony\Component\Filesystem\Filesystem; -use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmer; - -/** - * Computes the association between template names and their paths on the disk. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class TemplatePathsCacheWarmer extends CacheWarmer -{ - protected $finder; - protected $locator; - - public function __construct(TemplateFinderInterface $finder, TemplateLocator $locator) - { - $this->finder = $finder; - $this->locator = $locator; - } - - /** - * Warms up the cache. - * - * @param string $cacheDir The cache directory - */ - public function warmUp($cacheDir) - { - $filesystem = new Filesystem(); - $templates = []; - - foreach ($this->finder->findAllTemplates() as $template) { - $templates[$template->getLogicalName()] = rtrim($filesystem->makePathRelative($this->locator->locate($template), $cacheDir), '/'); - } - - $templates = str_replace("' => '", "' => __DIR__.'/", var_export($templates, true)); - - $this->writeCacheFile($cacheDir.'/templates.php', sprintf("translator) { $this->translator = $this->container->get('translator'); diff --git a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/ValidatorCacheWarmer.php b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/ValidatorCacheWarmer.php index aa893ea70a409..8569521bc599b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/ValidatorCacheWarmer.php +++ b/src/Symfony/Bundle/FrameworkBundle/CacheWarmer/ValidatorCacheWarmer.php @@ -12,7 +12,6 @@ namespace Symfony\Bundle\FrameworkBundle\CacheWarmer; use Doctrine\Common\Annotations\AnnotationException; -use Psr\Cache\CacheItemPoolInterface; use Symfony\Component\Cache\Adapter\ArrayAdapter; use Symfony\Component\Cache\Adapter\PhpArrayAdapter; use Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory; @@ -21,7 +20,6 @@ use Symfony\Component\Validator\Mapping\Loader\XmlFileLoader; use Symfony\Component\Validator\Mapping\Loader\YamlFileLoader; use Symfony\Component\Validator\ValidatorBuilder; -use Symfony\Component\Validator\ValidatorBuilderInterface; /** * Warms up XML and YAML validator metadata. @@ -33,17 +31,10 @@ class ValidatorCacheWarmer extends AbstractPhpFileCacheWarmer private $validatorBuilder; /** - * @param ValidatorBuilder $validatorBuilder - * @param string $phpArrayFile The PHP file where metadata are cached + * @param string $phpArrayFile The PHP file where metadata are cached */ - public function __construct($validatorBuilder, string $phpArrayFile) + public function __construct(ValidatorBuilder $validatorBuilder, string $phpArrayFile) { - if (!$validatorBuilder instanceof ValidatorBuilder && !$validatorBuilder instanceof ValidatorBuilderInterface) { - throw new \TypeError(sprintf('Argument 1 passed to %s() must be an instance of %s, %s given.', __METHOD__, ValidatorBuilder::class, \is_object($validatorBuilder) ? \get_class($validatorBuilder) : \gettype($validatorBuilder))); - } - if (2 < \func_num_args() && func_get_arg(2) instanceof CacheItemPoolInterface) { - @trigger_error(sprintf('The CacheItemPoolInterface $fallbackPool argument of "%s()" is deprecated since Symfony 4.2, you should not pass it anymore.', __METHOD__), E_USER_DEPRECATED); - } parent::__construct($phpArrayFile); $this->validatorBuilder = $validatorBuilder; } @@ -51,7 +42,7 @@ public function __construct($validatorBuilder, string $phpArrayFile) /** * {@inheritdoc} */ - protected function doWarmUp($cacheDir, ArrayAdapter $arrayAdapter) + protected function doWarmUp(string $cacheDir, ArrayAdapter $arrayAdapter) { if (!method_exists($this->validatorBuilder, 'getLoaders')) { return false; diff --git a/src/Symfony/Bundle/FrameworkBundle/Client.php b/src/Symfony/Bundle/FrameworkBundle/Client.php deleted file mode 100644 index 6450a4ec0022a..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Client.php +++ /dev/null @@ -1,206 +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; - -use Symfony\Component\BrowserKit\CookieJar; -use Symfony\Component\BrowserKit\History; -use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpKernel\HttpKernelBrowser; -use Symfony\Component\HttpKernel\KernelInterface; -use Symfony\Component\HttpKernel\Profiler\Profile as HttpProfile; - -/** - * Client simulates a browser and makes requests to a Kernel object. - * - * @deprecated since Symfony 4.3, use KernelBrowser instead. - */ -class Client extends HttpKernelBrowser -{ - private $hasPerformedRequest = false; - private $profiler = false; - private $reboot = true; - - /** - * {@inheritdoc} - */ - public function __construct(KernelInterface $kernel, array $server = [], History $history = null, CookieJar $cookieJar = null) - { - parent::__construct($kernel, $server, $history, $cookieJar); - } - - /** - * Returns the container. - * - * @return ContainerInterface|null Returns null when the Kernel has been shutdown or not started yet - */ - public function getContainer() - { - return $this->kernel->getContainer(); - } - - /** - * Returns the kernel. - * - * @return KernelInterface - */ - public function getKernel() - { - return $this->kernel; - } - - /** - * Gets the profile associated with the current Response. - * - * @return HttpProfile|false A Profile instance - */ - public function getProfile() - { - if (null === $this->response || !$this->kernel->getContainer()->has('profiler')) { - return false; - } - - return $this->kernel->getContainer()->get('profiler')->loadProfileFromResponse($this->response); - } - - /** - * Enables the profiler for the very next request. - * - * If the profiler is not enabled, the call to this method does nothing. - */ - public function enableProfiler() - { - if ($this->kernel->getContainer()->has('profiler')) { - $this->profiler = true; - } - } - - /** - * Disables kernel reboot between requests. - * - * By default, the Client reboots the Kernel for each request. This method - * allows to keep the same kernel across requests. - */ - public function disableReboot() - { - $this->reboot = false; - } - - /** - * Enables kernel reboot between requests. - */ - public function enableReboot() - { - $this->reboot = true; - } - - /** - * {@inheritdoc} - * - * @param Request $request A Request instance - * - * @return Response A Response instance - */ - protected function doRequest($request) - { - // avoid shutting down the Kernel if no request has been performed yet - // WebTestCase::createClient() boots the Kernel but do not handle a request - if ($this->hasPerformedRequest && $this->reboot) { - $this->kernel->shutdown(); - } else { - $this->hasPerformedRequest = true; - } - - if ($this->profiler) { - $this->profiler = false; - - $this->kernel->boot(); - $this->kernel->getContainer()->get('profiler')->enable(); - } - - return parent::doRequest($request); - } - - /** - * {@inheritdoc} - * - * @param Request $request A Request instance - * - * @return Response A Response instance - */ - protected function doRequestInProcess($request) - { - $response = parent::doRequestInProcess($request); - - $this->profiler = false; - - return $response; - } - - /** - * Returns the script to execute when the request must be insulated. - * - * It assumes that the autoloader is named 'autoload.php' and that it is - * stored in the same directory as the kernel (this is the case for the - * Symfony Standard Edition). If this is not your case, create your own - * client and override this method. - * - * @param Request $request A Request instance - * - * @return string The script content - */ - protected function getScript($request) - { - $kernel = var_export(serialize($this->kernel), true); - $request = var_export(serialize($request), true); - $errorReporting = error_reporting(); - - $requires = ''; - foreach (get_declared_classes() as $class) { - if (0 === strpos($class, 'ComposerAutoloaderInit')) { - $r = new \ReflectionClass($class); - $file = \dirname($r->getFileName(), 2).'/autoload.php'; - if (file_exists($file)) { - $requires .= 'require_once '.var_export($file, true).";\n"; - } - } - } - - if (!$requires) { - throw new \RuntimeException('Composer autoloader not found.'); - } - - $requires .= 'require_once '.var_export((new \ReflectionObject($this->kernel))->getFileName(), true).";\n"; - - $profilerCode = ''; - if ($this->profiler) { - $profilerCode = '$kernel->getContainer()->get(\'profiler\')->enable();'; - } - - $code = <<boot(); -$profilerCode - -\$request = unserialize($request); -EOF; - - return $code.$this->getHandleScript(); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/AbstractConfigCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/AbstractConfigCommand.php index c038133975302..232348d0360c8 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/AbstractConfigCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/AbstractConfigCommand.php @@ -59,7 +59,7 @@ protected function listBundles($output) /** * @return ExtensionInterface */ - protected function findExtension($name) + protected function findExtension(string $name) { $bundles = $this->initializeBundles(); $minScore = INF; diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/AssetsInstallCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/AssetsInstallCommand.php index 396dcbaf659c0..b02b6a489c04c 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/AssetsInstallCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/AssetsInstallCommand.php @@ -44,14 +44,10 @@ class AssetsInstallCommand extends Command private $filesystem; private $projectDir; - public function __construct(Filesystem $filesystem, string $projectDir = null) + public function __construct(Filesystem $filesystem, string $projectDir) { parent::__construct(); - if (null === $projectDir) { - @trigger_error(sprintf('Not passing the project directory to the constructor of %s is deprecated since Symfony 4.3 and will not be supported in 5.0.', __CLASS__), E_USER_DEPRECATED); - } - $this->filesystem = $filesystem; $this->projectDir = $projectDir; } diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerAwareCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerAwareCommand.php deleted file mode 100644 index 7b01a55ef8af5..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerAwareCommand.php +++ /dev/null @@ -1,60 +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\Command; - -use Symfony\Component\Console\Command\Command; -use Symfony\Component\DependencyInjection\ContainerAwareInterface; -use Symfony\Component\DependencyInjection\ContainerInterface; - -@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use "%s" with dependency injection instead.', ContainerAwareCommand::class, Command::class), E_USER_DEPRECATED); - -/** - * Command. - * - * @author Fabien Potencier - * - * @deprecated since Symfony 4.2, use {@see Command} instead. - */ -abstract class ContainerAwareCommand extends Command implements ContainerAwareInterface -{ - /** - * @var ContainerInterface|null - */ - private $container; - - /** - * @return ContainerInterface - * - * @throws \LogicException - */ - protected function getContainer() - { - if (null === $this->container) { - $application = $this->getApplication(); - if (null === $application) { - throw new \LogicException('The container cannot be retrieved as the application instance is not yet set.'); - } - - $this->container = $application->getKernel()->getContainer(); - } - - return $this->container; - } - - /** - * {@inheritdoc} - */ - public function setContainer(ContainerInterface $container = null) - { - $this->container = $container; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php index 4b55579d689d5..39590088fcd84 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/ContainerDebugCommand.php @@ -50,7 +50,6 @@ protected function configure() $this ->setDefinition([ new InputArgument('name', InputArgument::OPTIONAL, 'A service name (foo)'), - new InputOption('show-private', null, InputOption::VALUE_NONE, 'Used to show public *and* private services (deprecated)'), new InputOption('show-arguments', null, InputOption::VALUE_NONE, 'Used to show arguments in services'), new InputOption('show-hidden', null, InputOption::VALUE_NONE, 'Used to show hidden (internal) services'), new InputOption('tag', null, InputOption::VALUE_REQUIRED, 'Shows all services with a specific tag'), @@ -116,10 +115,6 @@ protected function configure() */ protected function execute(InputInterface $input, OutputInterface $output): int { - if ($input->getOption('show-private')) { - @trigger_error('The "--show-private" option no longer has any effect and is deprecated since Symfony 4.1.', E_USER_DEPRECATED); - } - $io = new SymfonyStyle($input, $output); $errorIo = $io->getErrorStyle(); diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/TranslationDebugCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/TranslationDebugCommand.php index 124274d47427a..24290a43c9043 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/TranslationDebugCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/TranslationDebugCommand.php @@ -26,7 +26,6 @@ use Symfony\Component\Translation\MessageCatalogue; use Symfony\Component\Translation\Reader\TranslationReaderInterface; use Symfony\Component\Translation\Translator; -use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface; use Symfony\Contracts\Translation\TranslatorInterface; /** @@ -53,14 +52,8 @@ class TranslationDebugCommand extends Command private $transPaths; private $viewsPaths; - /** - * @param TranslatorInterface $translator - */ - public function __construct($translator, TranslationReaderInterface $reader, ExtractorInterface $extractor, string $defaultTransPath = null, string $defaultViewsPath = null, array $transPaths = [], array $viewsPaths = []) + public function __construct(TranslatorInterface $translator, TranslationReaderInterface $reader, ExtractorInterface $extractor, string $defaultTransPath = null, string $defaultViewsPath = null, array $transPaths = [], array $viewsPaths = []) { - if (!$translator instanceof LegacyTranslatorInterface && !$translator instanceof TranslatorInterface) { - throw new \TypeError(sprintf('Argument 1 passed to %s() must be an instance of %s, %s given.', __METHOD__, TranslatorInterface::class, \is_object($translator) ? \get_class($translator) : \gettype($translator))); - } parent::__construct(); $this->translator = $translator; @@ -132,28 +125,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int $domain = $input->getOption('domain'); /** @var KernelInterface $kernel */ $kernel = $this->getApplication()->getKernel(); - $rootDir = $kernel->getContainer()->getParameter('kernel.root_dir'); // Define Root Paths $transPaths = $this->transPaths; - if (is_dir($dir = $rootDir.'/Resources/translations')) { - if ($dir !== $this->defaultTransPath) { - $notice = sprintf('Storing translations in the "%s" directory is deprecated since Symfony 4.2, ', $dir); - @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); - } - $transPaths[] = $dir; - } if ($this->defaultTransPath) { $transPaths[] = $this->defaultTransPath; } $viewsPaths = $this->viewsPaths; - if (is_dir($dir = $rootDir.'/Resources/views')) { - if ($dir !== $this->defaultViewsPath) { - $notice = sprintf('Loading Twig templates from the "%s" directory is deprecated since Symfony 4.2, ', $dir); - @trigger_error($notice.($this->defaultViewsPath ? sprintf('use the "%s" directory instead.', $this->defaultViewsPath) : 'configure and use "twig.default_path" instead.'), E_USER_DEPRECATED); - } - $viewsPaths[] = $dir; - } if ($this->defaultViewsPath) { $viewsPaths[] = $this->defaultViewsPath; } @@ -168,38 +146,15 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($this->defaultTransPath) { $transPaths[] = $this->defaultTransPath; } - if (is_dir($dir = sprintf('%s/Resources/%s/translations', $rootDir, $bundle->getName()))) { - $transPaths[] = $dir; - $notice = sprintf('Storing translations files for "%s" in the "%s" directory is deprecated since Symfony 4.2, ', $dir, $bundle->getName()); - @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); - } if ($this->defaultViewsPath) { $viewsPaths[] = $this->defaultViewsPath; } - if (is_dir($dir = sprintf('%s/Resources/%s/views', $rootDir, $bundle->getName()))) { - $viewsPaths[] = $dir; - $notice = sprintf('Loading Twig templates for "%s" from the "%s" directory is deprecated since Symfony 4.2, ', $bundle->getName(), $dir); - @trigger_error($notice.($this->defaultViewsPath ? sprintf('use the "%s" directory instead.', $this->defaultViewsPath) : 'configure and use "twig.default_path" instead.'), E_USER_DEPRECATED); - } } catch (\InvalidArgumentException $e) { // such a bundle does not exist, so treat the argument as path $path = $input->getArgument('bundle'); $transPaths = [$path.'/translations']; - if (is_dir($dir = $path.'/Resources/translations')) { - if ($dir !== $this->defaultTransPath) { - @trigger_error(sprintf('Storing translations in the "%s" directory is deprecated since Symfony 4.2, use the "%s" directory instead.', $dir, $path.'/translations'), E_USER_DEPRECATED); - } - $transPaths[] = $dir; - } - $viewsPaths = [$path.'/templates']; - if (is_dir($dir = $path.'/Resources/views')) { - if ($dir !== $this->defaultViewsPath) { - @trigger_error(sprintf('Loading Twig templates from the "%s" directory is deprecated since Symfony 4.2, use the "%s" directory instead.', $dir, $path.'/templates'), E_USER_DEPRECATED); - } - $viewsPaths[] = $dir; - } if (!is_dir($transPaths[0]) && !isset($transPaths[1])) { throw new InvalidArgumentException(sprintf('"%s" is neither an enabled bundle nor a directory.', $transPaths[0])); @@ -210,16 +165,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int $bundleDir = $bundle->getPath(); $transPaths[] = is_dir($bundleDir.'/Resources/translations') ? $bundleDir.'/Resources/translations' : $bundle->getPath().'/translations'; $viewsPaths[] = is_dir($bundleDir.'/Resources/views') ? $bundleDir.'/Resources/views' : $bundle->getPath().'/templates'; - if (is_dir($deprecatedPath = sprintf('%s/Resources/%s/translations', $rootDir, $bundle->getName()))) { - $transPaths[] = $deprecatedPath; - $notice = sprintf('Storing translations files for "%s" in the "%s" directory is deprecated since Symfony 4.2, ', $bundle->getName(), $deprecatedPath); - @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); - } - if (is_dir($deprecatedPath = sprintf('%s/Resources/%s/views', $rootDir, $bundle->getName()))) { - $viewsPaths[] = $deprecatedPath; - $notice = sprintf('Loading Twig templates for "%s" from the "%s" directory is deprecated since Symfony 4.2, ', $bundle->getName(), $deprecatedPath); - @trigger_error($notice.($this->defaultViewsPath ? sprintf('use the "%s" directory instead.', $this->defaultViewsPath) : 'configure and use "twig.default_path" instead.'), E_USER_DEPRECATED); - } } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Command/TranslationUpdateCommand.php b/src/Symfony/Bundle/FrameworkBundle/Command/TranslationUpdateCommand.php index 727c18c4275c2..e717b073893b4 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Command/TranslationUpdateCommand.php +++ b/src/Symfony/Bundle/FrameworkBundle/Command/TranslationUpdateCommand.php @@ -136,28 +136,13 @@ protected function execute(InputInterface $input, OutputInterface $output): int } /** @var KernelInterface $kernel */ $kernel = $this->getApplication()->getKernel(); - $rootDir = $kernel->getContainer()->getParameter('kernel.root_dir'); // Define Root Paths $transPaths = $this->transPaths; - if (is_dir($dir = $rootDir.'/Resources/translations')) { - if ($dir !== $this->defaultTransPath) { - $notice = sprintf('Storing translations in the "%s" directory is deprecated since Symfony 4.2, ', $dir); - @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); - } - $transPaths[] = $dir; - } if ($this->defaultTransPath) { $transPaths[] = $this->defaultTransPath; } $viewsPaths = $this->viewsPaths; - if (is_dir($dir = $rootDir.'/Resources/views')) { - if ($dir !== $this->defaultViewsPath) { - $notice = sprintf('Storing templates in the "%s" directory is deprecated since Symfony 4.2, ', $dir); - @trigger_error($notice.($this->defaultViewsPath ? sprintf('use the "%s" directory instead.', $this->defaultViewsPath) : 'configure and use "twig.default_path" instead.'), E_USER_DEPRECATED); - } - $viewsPaths[] = $dir; - } if ($this->defaultViewsPath) { $viewsPaths[] = $this->defaultViewsPath; } @@ -173,39 +158,16 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($this->defaultTransPath) { $transPaths[] = $this->defaultTransPath; } - if (is_dir($dir = sprintf('%s/Resources/%s/translations', $rootDir, $foundBundle->getName()))) { - $transPaths[] = $dir; - $notice = sprintf('Storing translations files for "%s" in the "%s" directory is deprecated since Symfony 4.2, ', $foundBundle->getName(), $dir); - @trigger_error($notice.($this->defaultTransPath ? sprintf('use the "%s" directory instead.', $this->defaultTransPath) : 'configure and use "framework.translator.default_path" instead.'), E_USER_DEPRECATED); - } if ($this->defaultViewsPath) { $viewsPaths[] = $this->defaultViewsPath; } - if (is_dir($dir = sprintf('%s/Resources/%s/views', $rootDir, $foundBundle->getName()))) { - $viewsPaths[] = $dir; - $notice = sprintf('Storing templates for "%s" in the "%s" directory is deprecated since Symfony 4.2, ', $foundBundle->getName(), $dir); - @trigger_error($notice.($this->defaultViewsPath ? sprintf('use the "%s" directory instead.', $this->defaultViewsPath) : 'configure and use "twig.default_path" instead.'), E_USER_DEPRECATED); - } $currentName = $foundBundle->getName(); } catch (\InvalidArgumentException $e) { // such a bundle does not exist, so treat the argument as path $path = $input->getArgument('bundle'); $transPaths = [$path.'/translations']; - if (is_dir($dir = $path.'/Resources/translations')) { - if ($dir !== $this->defaultTransPath) { - @trigger_error(sprintf('Storing translations in the "%s" directory is deprecated since Symfony 4.2, use the "%s" directory instead.', $dir, $path.'/translations'), E_USER_DEPRECATED); - } - $transPaths[] = $dir; - } - $viewsPaths = [$path.'/templates']; - if (is_dir($dir = $path.'/Resources/views')) { - if ($dir !== $this->defaultViewsPath) { - @trigger_error(sprintf('Storing templates in the "%s" directory is deprecated since Symfony 4.2, use the "%s" directory instead.', $dir, $path.'/templates'), E_USER_DEPRECATED); - } - $viewsPaths[] = $dir; - } if (!is_dir($transPaths[0]) && !isset($transPaths[1])) { throw new InvalidArgumentException(sprintf('"%s" is neither an enabled bundle nor a directory.', $transPaths[0])); diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php b/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php index bc4c75585d7b6..2f9b31b18efa2 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php +++ b/src/Symfony/Bundle/FrameworkBundle/Controller/AbstractController.php @@ -13,19 +13,36 @@ use Doctrine\Common\Persistence\ManagerRegistry; use Psr\Container\ContainerInterface; +use Psr\Link\LinkInterface; use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException; use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface; +use Symfony\Component\Form\Extension\Core\Type\FormType; +use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormFactoryInterface; +use Symfony\Component\Form\FormInterface; +use Symfony\Component\HttpFoundation\BinaryFileResponse; +use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\RedirectResponse; +use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\ResponseHeaderBag; use Symfony\Component\HttpFoundation\Session\SessionInterface; +use Symfony\Component\HttpFoundation\StreamedResponse; +use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\HttpKernel\HttpKernelInterface; +use Symfony\Component\Messenger\Envelope; use Symfony\Component\Messenger\MessageBusInterface; +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\RouterInterface; use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; +use Symfony\Component\Security\Core\Exception\AccessDeniedException; +use Symfony\Component\Security\Csrf\CsrfToken; use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Symfony\Component\Serializer\SerializerInterface; -use Symfony\Component\Templating\EngineInterface; +use Symfony\Component\WebLink\EventListener\AddLinkHeaderListener; +use Symfony\Component\WebLink\GenericLinkProvider; use Symfony\Contracts\Service\ServiceSubscriberInterface; use Twig\Environment; @@ -36,8 +53,6 @@ */ abstract class AbstractController implements ServiceSubscriberInterface { - use ControllerTrait; - /** * @var ContainerInterface */ @@ -59,8 +74,6 @@ public function setContainer(ContainerInterface $container): ?ContainerInterface * Gets a container parameter by its name. * * @return mixed - * - * @final */ protected function getParameter(string $name) { @@ -80,7 +93,6 @@ public static function getSubscribedServices() 'serializer' => '?'.SerializerInterface::class, 'session' => '?'.SessionInterface::class, 'security.authorization_checker' => '?'.AuthorizationCheckerInterface::class, - 'templating' => '?'.EngineInterface::class, 'twig' => '?'.Environment::class, 'doctrine' => '?'.ManagerRegistry::class, 'form.factory' => '?'.FormFactoryInterface::class, @@ -91,4 +103,325 @@ public static function getSubscribedServices() 'messenger.default_bus' => '?'.MessageBusInterface::class, ]; } + + /** + * Returns true if the service id is defined. + */ + protected function has(string $id): bool + { + return $this->container->has($id); + } + + /** + * Gets a container service by its id. + * + * @return object The service + */ + protected function get(string $id): object + { + return $this->container->get($id); + } + + /** + * Generates a URL from the given parameters. + * + * @see UrlGeneratorInterface + */ + protected function generateUrl(string $route, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string + { + return $this->container->get('router')->generate($route, $parameters, $referenceType); + } + + /** + * Forwards the request to another controller. + * + * @param string $controller The controller name (a string like Bundle\BlogBundle\Controller\PostController::indexAction) + */ + protected function forward(string $controller, array $path = [], array $query = []): Response + { + $request = $this->container->get('request_stack')->getCurrentRequest(); + $path['_controller'] = $controller; + $subRequest = $request->duplicate($query, null, $path); + + return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST); + } + + /** + * Returns a RedirectResponse to the given URL. + */ + protected function redirect(string $url, int $status = 302): RedirectResponse + { + return new RedirectResponse($url, $status); + } + + /** + * Returns a RedirectResponse to the given route with the given parameters. + */ + protected function redirectToRoute(string $route, array $parameters = [], int $status = 302): RedirectResponse + { + return $this->redirect($this->generateUrl($route, $parameters), $status); + } + + /** + * Returns a JsonResponse that uses the serializer component if enabled, or json_encode. + */ + protected function json($data, int $status = 200, array $headers = [], array $context = []): JsonResponse + { + if ($this->container->has('serializer')) { + $json = $this->container->get('serializer')->serialize($data, 'json', array_merge([ + 'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS, + ], $context)); + + return new JsonResponse($json, $status, $headers, true); + } + + return new JsonResponse($data, $status, $headers); + } + + /** + * Returns a BinaryFileResponse object with original or customized file name and disposition header. + * + * @param \SplFileInfo|string $file File object or path to file to be sent as response + */ + protected function file($file, string $fileName = null, string $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse + { + $response = new BinaryFileResponse($file); + $response->setContentDisposition($disposition, null === $fileName ? $response->getFile()->getFilename() : $fileName); + + return $response; + } + + /** + * Adds a flash message to the current session for type. + * + * @throws \LogicException + */ + protected function addFlash(string $type, string $message): void + { + if (!$this->container->has('session')) { + throw new \LogicException('You can not use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".'); + } + + $this->container->get('session')->getFlashBag()->add($type, $message); + } + + /** + * Checks if the attributes are granted against the current authentication token and optionally supplied subject. + * + * @throws \LogicException + */ + protected function isGranted($attributes, $subject = null): bool + { + if (!$this->container->has('security.authorization_checker')) { + throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".'); + } + + return $this->container->get('security.authorization_checker')->isGranted($attributes, $subject); + } + + /** + * Throws an exception unless the attributes are granted against the current authentication token and optionally + * supplied subject. + * + * @throws AccessDeniedException + */ + protected function denyAccessUnlessGranted($attributes, $subject = null, string $message = 'Access Denied.'): void + { + if (!$this->isGranted($attributes, $subject)) { + $exception = $this->createAccessDeniedException($message); + $exception->setAttributes($attributes); + $exception->setSubject($subject); + + throw $exception; + } + } + + /** + * Returns a rendered view. + */ + protected function renderView(string $view, array $parameters = []): string + { + if (!$this->container->has('twig')) { + throw new \LogicException('You can not use the "renderView" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".'); + } + + return $this->container->get('twig')->render($view, $parameters); + } + + /** + * Renders a view. + */ + protected function render(string $view, array $parameters = [], Response $response = null): Response + { + $content = $this->renderView($view, $parameters); + + if (null === $response) { + $response = new Response(); + } + + $response->setContent($content); + + return $response; + } + + /** + * Streams a view. + */ + protected function stream(string $view, array $parameters = [], StreamedResponse $response = null): StreamedResponse + { + if (!$this->container->has('twig')) { + throw new \LogicException('You can not use the "stream" method if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".'); + } + + $twig = $this->container->get('twig'); + + $callback = function () use ($twig, $view, $parameters) { + $twig->display($view, $parameters); + }; + + if (null === $response) { + return new StreamedResponse($callback); + } + + $response->setCallback($callback); + + return $response; + } + + /** + * Returns a NotFoundHttpException. + * + * This will result in a 404 response code. Usage example: + * + * throw $this->createNotFoundException('Page not found!'); + */ + protected function createNotFoundException(string $message = 'Not Found', \Throwable $previous = null): NotFoundHttpException + { + return new NotFoundHttpException($message, $previous); + } + + /** + * Returns an AccessDeniedException. + * + * This will result in a 403 response code. Usage example: + * + * throw $this->createAccessDeniedException('Unable to access this page!'); + * + * @throws \LogicException If the Security component is not available + */ + protected function createAccessDeniedException(string $message = 'Access Denied.', \Throwable $previous = null): AccessDeniedException + { + if (!class_exists(AccessDeniedException::class)) { + throw new \LogicException('You can not use the "createAccessDeniedException" method if the Security component is not available. Try running "composer require symfony/security-bundle".'); + } + + return new AccessDeniedException($message, $previous); + } + + /** + * Creates and returns a Form instance from the type of the form. + */ + protected function createForm(string $type, $data = null, array $options = []): FormInterface + { + return $this->container->get('form.factory')->create($type, $data, $options); + } + + /** + * Creates and returns a form builder instance. + */ + protected function createFormBuilder($data = null, array $options = []): FormBuilderInterface + { + return $this->container->get('form.factory')->createBuilder(FormType::class, $data, $options); + } + + /** + * Shortcut to return the Doctrine Registry service. + * + * @throws \LogicException If DoctrineBundle is not available + */ + protected function getDoctrine(): ManagerRegistry + { + if (!$this->container->has('doctrine')) { + throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".'); + } + + return $this->container->get('doctrine'); + } + + /** + * Get a user from the Security Token Storage. + * + * @return mixed + * + * @throws \LogicException If SecurityBundle is not available + * + * @see TokenInterface::getUser() + */ + protected function getUser() + { + if (!$this->container->has('security.token_storage')) { + throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".'); + } + + if (null === $token = $this->container->get('security.token_storage')->getToken()) { + return null; + } + + if (!\is_object($user = $token->getUser())) { + // e.g. anonymous authentication + return null; + } + + return $user; + } + + /** + * Checks the validity of a CSRF token. + * + * @param string $id The id used when generating the token + * @param string|null $token The actual token sent with the request that should be validated + */ + protected function isCsrfTokenValid(string $id, ?string $token): bool + { + if (!$this->container->has('security.csrf.token_manager')) { + throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".'); + } + + return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id, $token)); + } + + /** + * Dispatches a message to the bus. + * + * @param object|Envelope $message The message or the message pre-wrapped in an envelope + */ + protected function dispatchMessage($message, array $stamps = []): Envelope + { + if (!$this->container->has('messenger.default_bus')) { + $message = class_exists(Envelope::class) ? 'You need to define the "messenger.default_bus" configuration option.' : 'Try running "composer require symfony/messenger".'; + throw new \LogicException('The message bus is not enabled in your application. '.$message); + } + + return $this->container->get('messenger.default_bus')->dispatch($message, $stamps); + } + + /** + * Adds a Link HTTP header to the current response. + * + * @see https://tools.ietf.org/html/rfc5988 + */ + protected function addLink(Request $request, LinkInterface $link): void + { + if (!class_exists(AddLinkHeaderListener::class)) { + throw new \LogicException('You can not use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".'); + } + + if (null === $linkProvider = $request->attributes->get('_links')) { + $request->attributes->set('_links', new GenericLinkProvider([$link])); + + return; + } + + $request->attributes->set('_links', $linkProvider->withLink($link)); + } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php b/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php deleted file mode 100644 index b6708db544506..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php +++ /dev/null @@ -1,42 +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\Controller; - -use Symfony\Component\DependencyInjection\ContainerAwareInterface; -use Symfony\Component\DependencyInjection\ContainerAwareTrait; - -/** - * Controller is a simple implementation of a Controller. - * - * It provides methods to common features needed in controllers. - * - * @deprecated since Symfony 4.2, use "Symfony\Bundle\FrameworkBundle\Controller\AbstractController" instead. - * - * @author Fabien Potencier - */ -abstract class Controller implements ContainerAwareInterface -{ - use ContainerAwareTrait; - use ControllerTrait; - - /** - * Gets a container configuration parameter by its name. - * - * @return mixed - * - * @final - */ - protected function getParameter(string $name) - { - return $this->container->getParameter($name); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerNameParser.php b/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerNameParser.php deleted file mode 100644 index 1a1112dbaeb23..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerNameParser.php +++ /dev/null @@ -1,146 +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\Controller; - -use Symfony\Component\HttpKernel\Bundle\BundleInterface; -use Symfony\Component\HttpKernel\KernelInterface; - -/** - * ControllerNameParser converts controller from the short notation a:b:c - * (BlogBundle:Post:index) to a fully-qualified class::method string - * (Bundle\BlogBundle\Controller\PostController::indexAction). - * - * @author Fabien Potencier - * - * @deprecated since Symfony 4.1 - */ -class ControllerNameParser -{ - protected $kernel; - - public function __construct(KernelInterface $kernel, bool $triggerDeprecation = true) - { - $this->kernel = $kernel; - - if ($triggerDeprecation) { - @trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.1.', __CLASS__), E_USER_DEPRECATED); - } - } - - /** - * Converts a short notation a:b:c to a class::method. - * - * @param string $controller A short notation controller (a:b:c) - * - * @return string A string in the class::method notation - * - * @throws \InvalidArgumentException when the specified bundle is not enabled - * or the controller cannot be found - */ - public function parse($controller) - { - if (2 > \func_num_args() || func_get_arg(1)) { - @trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.1.', __CLASS__), E_USER_DEPRECATED); - } - - $parts = explode(':', $controller); - if (3 !== \count($parts) || \in_array('', $parts, true)) { - throw new \InvalidArgumentException(sprintf('The "%s" controller is not a valid "a:b:c" controller string.', $controller)); - } - - $originalController = $controller; - list($bundleName, $controller, $action) = $parts; - $controller = str_replace('/', '\\', $controller); - - try { - // this throws an exception if there is no such bundle - $bundle = $this->kernel->getBundle($bundleName); - } catch (\InvalidArgumentException $e) { - $message = sprintf( - 'The "%s" (from the _controller value "%s") does not exist or is not enabled in your kernel!', - $bundleName, - $originalController - ); - - if ($alternative = $this->findAlternative($bundleName)) { - $message .= sprintf(' Did you mean "%s:%s:%s"?', $alternative, $controller, $action); - } - - throw new \InvalidArgumentException($message, 0, $e); - } - - $try = $bundle->getNamespace().'\\Controller\\'.$controller.'Controller'; - if (class_exists($try)) { - return $try.'::'.$action.'Action'; - } - - throw new \InvalidArgumentException(sprintf('The _controller value "%s:%s:%s" maps to a "%s" class, but this class was not found. Create this class or check the spelling of the class and its namespace.', $bundleName, $controller, $action, $try)); - } - - /** - * Converts a class::method notation to a short one (a:b:c). - * - * @param string $controller A string in the class::method notation - * - * @return string A short notation controller (a:b:c) - * - * @throws \InvalidArgumentException when the controller is not valid or cannot be found in any bundle - */ - public function build($controller) - { - @trigger_error(sprintf('The %s class is deprecated since Symfony 4.1.', __CLASS__), E_USER_DEPRECATED); - - if (0 === preg_match('#^(.*?\\\\Controller\\\\(.+)Controller)::(.+)Action$#', $controller, $match)) { - throw new \InvalidArgumentException(sprintf('The "%s" controller is not a valid "class::method" string.', $controller)); - } - - $className = $match[1]; - $controllerName = $match[2]; - $actionName = $match[3]; - foreach ($this->kernel->getBundles() as $name => $bundle) { - if (0 !== strpos($className, $bundle->getNamespace())) { - continue; - } - - return sprintf('%s:%s:%s', $name, $controllerName, $actionName); - } - - throw new \InvalidArgumentException(sprintf('Unable to find a bundle that defines controller "%s".', $controller)); - } - - /** - * Attempts to find a bundle that is *similar* to the given bundle name. - */ - private function findAlternative(string $nonExistentBundleName): ?string - { - $bundleNames = array_map(function (BundleInterface $b) { - return $b->getName(); - }, $this->kernel->getBundles()); - - $alternative = null; - $shortest = null; - foreach ($bundleNames as $bundleName) { - // if there's a partial match, return it immediately - if (false !== strpos($bundleName, $nonExistentBundleName)) { - return $bundleName; - } - - $lev = levenshtein($nonExistentBundleName, $bundleName); - if ($lev <= \strlen($nonExistentBundleName) / 3 && (null === $alternative || $lev < $shortest)) { - $alternative = $bundleName; - $shortest = $lev; - } - } - - return $alternative; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerResolver.php b/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerResolver.php index e4f5e5dfa54a3..859d1c200ed4e 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerResolver.php +++ b/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerResolver.php @@ -11,75 +11,32 @@ namespace Symfony\Bundle\FrameworkBundle\Controller; -use Psr\Log\LoggerInterface; use Symfony\Component\DependencyInjection\ContainerAwareInterface; -use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpKernel\Controller\ContainerControllerResolver; /** * @author Fabien Potencier * - * @final since Symfony 4.4 + * @final */ class ControllerResolver extends ContainerControllerResolver { - /** - * @deprecated since Symfony 4.4 - */ - protected $parser; - - /** - * @param LoggerInterface|null $logger - */ - public function __construct(ContainerInterface $container, $logger = null) - { - if ($logger instanceof ControllerNameParser) { - @trigger_error(sprintf('Passing a "%s" instance as 2nd argument to "%s()" is deprecated since Symfony 4.4, pass a "%s" instance or null instead.', ControllerNameParser::class, __METHOD__, LoggerInterface::class), E_USER_DEPRECATED); - $this->parser = $logger; - $logger = 2 < \func_num_args() ? func_get_arg(2) : null; - } elseif (2 < \func_num_args() && func_get_arg(2) instanceof ControllerNameParser) { - $this->parser = func_get_arg(2); - } elseif ($logger && !$logger instanceof LoggerInterface) { - throw new \TypeError(sprintf('Argument 2 of "%s()" must be an instance of "%s" or null, "%s" given.', __METHOD__, LoggerInterface::class, \is_object($logger) ? \get_class($logger) : \gettype($logger)), E_USER_DEPRECATED); - } - - parent::__construct($container, $logger); - } - - /** - * {@inheritdoc} - */ - protected function createController($controller) - { - if ($this->parser && false === strpos($controller, '::') && 2 === substr_count($controller, ':')) { - // controller in the a:b:c notation then - $deprecatedNotation = $controller; - $controller = $this->parser->parse($deprecatedNotation, false); - - @trigger_error(sprintf('Referencing controllers with %s is deprecated since Symfony 4.1. Use %s instead.', $deprecatedNotation, $controller), E_USER_DEPRECATED); - } - - return parent::createController($controller); - } - /** * {@inheritdoc} */ - protected function instantiateController($class) + protected function instantiateController($class): object { return $this->configureController(parent::instantiateController($class), $class); } - private function configureController($controller, string $class) + private function configureController($controller, string $class): object { if ($controller instanceof ContainerAwareInterface) { $controller->setContainer($this->container); } if ($controller instanceof AbstractController) { if (null === $previousContainer = $controller->setContainer($this->container)) { - @trigger_error(sprintf('Auto-injection of the container for "%s" is deprecated since Symfony 4.2. Configure it as a service instead.', $class), E_USER_DEPRECATED); - // To be uncommented on Symfony 5: - //throw new \LogicException(sprintf('"%s" has no container set, did you forget to define it as a service subscriber?', $class)); + throw new \LogicException(sprintf('"%s" has no container set, did you forget to define it as a service subscriber?', $class)); } else { $controller->setContainer($previousContainer); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerTrait.php b/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerTrait.php deleted file mode 100644 index e5a1e109fa7b0..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerTrait.php +++ /dev/null @@ -1,437 +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\Controller; - -use Doctrine\Common\Persistence\ManagerRegistry; -use Psr\Container\ContainerInterface; -use Psr\Link\LinkInterface; -use Symfony\Component\Form\Extension\Core\Type\FormType; -use Symfony\Component\Form\FormBuilderInterface; -use Symfony\Component\Form\FormInterface; -use Symfony\Component\HttpFoundation\BinaryFileResponse; -use Symfony\Component\HttpFoundation\JsonResponse; -use Symfony\Component\HttpFoundation\RedirectResponse; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpFoundation\ResponseHeaderBag; -use Symfony\Component\HttpFoundation\StreamedResponse; -use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; -use Symfony\Component\HttpKernel\HttpKernelInterface; -use Symfony\Component\Messenger\Envelope; -use Symfony\Component\Messenger\Stamp\StampInterface; -use Symfony\Component\Routing\Generator\UrlGeneratorInterface; -use Symfony\Component\Security\Core\Exception\AccessDeniedException; -use Symfony\Component\Security\Csrf\CsrfToken; -use Symfony\Component\WebLink\EventListener\AddLinkHeaderListener; -use Symfony\Component\WebLink\GenericLinkProvider; - -/** - * Common features needed in controllers. - * - * @author Fabien Potencier - * - * @internal - * - * @property ContainerInterface $container - */ -trait ControllerTrait -{ - /** - * Returns true if the service id is defined. - * - * @final - */ - protected function has(string $id): bool - { - return $this->container->has($id); - } - - /** - * Gets a container service by its id. - * - * @return object The service - * - * @final - */ - protected function get(string $id) - { - return $this->container->get($id); - } - - /** - * Generates a URL from the given parameters. - * - * @see UrlGeneratorInterface - * - * @final - */ - protected function generateUrl(string $route, array $parameters = [], int $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH): string - { - return $this->container->get('router')->generate($route, $parameters, $referenceType); - } - - /** - * Forwards the request to another controller. - * - * @param string $controller The controller name (a string like Bundle\BlogBundle\Controller\PostController::indexAction) - * - * @final - */ - protected function forward(string $controller, array $path = [], array $query = []): Response - { - $request = $this->container->get('request_stack')->getCurrentRequest(); - $path['_controller'] = $controller; - $subRequest = $request->duplicate($query, null, $path); - - return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST); - } - - /** - * Returns a RedirectResponse to the given URL. - * - * @final - */ - protected function redirect(string $url, int $status = 302): RedirectResponse - { - return new RedirectResponse($url, $status); - } - - /** - * Returns a RedirectResponse to the given route with the given parameters. - * - * @final - */ - protected function redirectToRoute(string $route, array $parameters = [], int $status = 302): RedirectResponse - { - return $this->redirect($this->generateUrl($route, $parameters), $status); - } - - /** - * Returns a JsonResponse that uses the serializer component if enabled, or json_encode. - * - * @final - */ - protected function json($data, int $status = 200, array $headers = [], array $context = []): JsonResponse - { - if ($this->container->has('serializer')) { - $json = $this->container->get('serializer')->serialize($data, 'json', array_merge([ - 'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS, - ], $context)); - - return new JsonResponse($json, $status, $headers, true); - } - - return new JsonResponse($data, $status, $headers); - } - - /** - * Returns a BinaryFileResponse object with original or customized file name and disposition header. - * - * @param \SplFileInfo|string $file File object or path to file to be sent as response - * - * @final - */ - protected function file($file, string $fileName = null, string $disposition = ResponseHeaderBag::DISPOSITION_ATTACHMENT): BinaryFileResponse - { - $response = new BinaryFileResponse($file); - $response->setContentDisposition($disposition, null === $fileName ? $response->getFile()->getFilename() : $fileName); - - return $response; - } - - /** - * Adds a flash message to the current session for type. - * - * @throws \LogicException - * - * @final - */ - protected function addFlash(string $type, string $message) - { - if (!$this->container->has('session')) { - throw new \LogicException('You can not use the addFlash method if sessions are disabled. Enable them in "config/packages/framework.yaml".'); - } - - $this->container->get('session')->getFlashBag()->add($type, $message); - } - - /** - * Checks if the attributes are granted against the current authentication token and optionally supplied subject. - * - * @throws \LogicException - * - * @final - */ - protected function isGranted($attributes, $subject = null): bool - { - if (!$this->container->has('security.authorization_checker')) { - throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".'); - } - - return $this->container->get('security.authorization_checker')->isGranted($attributes, $subject); - } - - /** - * Throws an exception unless the attributes are granted against the current authentication token and optionally - * supplied subject. - * - * @throws AccessDeniedException - * - * @final - */ - protected function denyAccessUnlessGranted($attributes, $subject = null, string $message = 'Access Denied.') - { - if (!$this->isGranted($attributes, $subject)) { - $exception = $this->createAccessDeniedException($message); - $exception->setAttributes($attributes); - $exception->setSubject($subject); - - throw $exception; - } - } - - /** - * Returns a rendered view. - * - * @final - */ - protected function renderView(string $view, array $parameters = []): string - { - if ($this->container->has('templating')) { - @trigger_error('Using the "templating" service is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - - return $this->container->get('templating')->render($view, $parameters); - } - - if (!$this->container->has('twig')) { - throw new \LogicException('You can not use the "renderView" method if the Templating Component or the Twig Bundle are not available. Try running "composer require symfony/twig-bundle".'); - } - - return $this->container->get('twig')->render($view, $parameters); - } - - /** - * Renders a view. - * - * @final - */ - protected function render(string $view, array $parameters = [], Response $response = null): Response - { - if ($this->container->has('templating')) { - @trigger_error('Using the "templating" service is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - - $content = $this->container->get('templating')->render($view, $parameters); - } elseif ($this->container->has('twig')) { - $content = $this->container->get('twig')->render($view, $parameters); - } else { - throw new \LogicException('You can not use the "render" method if the Templating Component or the Twig Bundle are not available. Try running "composer require symfony/twig-bundle".'); - } - - if (null === $response) { - $response = new Response(); - } - - $response->setContent($content); - - return $response; - } - - /** - * Streams a view. - * - * @final - */ - protected function stream(string $view, array $parameters = [], StreamedResponse $response = null): StreamedResponse - { - if ($this->container->has('templating')) { - @trigger_error('Using the "templating" service is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - - $templating = $this->container->get('templating'); - - $callback = function () use ($templating, $view, $parameters) { - $templating->stream($view, $parameters); - }; - } elseif ($this->container->has('twig')) { - $twig = $this->container->get('twig'); - - $callback = function () use ($twig, $view, $parameters) { - $twig->display($view, $parameters); - }; - } else { - throw new \LogicException('You can not use the "stream" method if the Templating Component or the Twig Bundle are not available. Try running "composer require symfony/twig-bundle".'); - } - - if (null === $response) { - return new StreamedResponse($callback); - } - - $response->setCallback($callback); - - return $response; - } - - /** - * Returns a NotFoundHttpException. - * - * This will result in a 404 response code. Usage example: - * - * throw $this->createNotFoundException('Page not found!'); - * - * @final - */ - protected function createNotFoundException(string $message = 'Not Found', \Throwable $previous = null): NotFoundHttpException - { - return new NotFoundHttpException($message, $previous); - } - - /** - * Returns an AccessDeniedException. - * - * This will result in a 403 response code. Usage example: - * - * throw $this->createAccessDeniedException('Unable to access this page!'); - * - * @throws \LogicException If the Security component is not available - * - * @final - */ - protected function createAccessDeniedException(string $message = 'Access Denied.', \Throwable $previous = null): AccessDeniedException - { - if (!class_exists(AccessDeniedException::class)) { - throw new \LogicException('You can not use the "createAccessDeniedException" method if the Security component is not available. Try running "composer require symfony/security-bundle".'); - } - - return new AccessDeniedException($message, $previous); - } - - /** - * Creates and returns a Form instance from the type of the form. - * - * @final - */ - protected function createForm(string $type, $data = null, array $options = []): FormInterface - { - return $this->container->get('form.factory')->create($type, $data, $options); - } - - /** - * Creates and returns a form builder instance. - * - * @final - */ - protected function createFormBuilder($data = null, array $options = []): FormBuilderInterface - { - return $this->container->get('form.factory')->createBuilder(FormType::class, $data, $options); - } - - /** - * Shortcut to return the Doctrine Registry service. - * - * @throws \LogicException If DoctrineBundle is not available - * - * @final - */ - protected function getDoctrine(): ManagerRegistry - { - if (!$this->container->has('doctrine')) { - throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".'); - } - - return $this->container->get('doctrine'); - } - - /** - * Get a user from the Security Token Storage. - * - * @return object|null - * - * @throws \LogicException If SecurityBundle is not available - * - * @see TokenInterface::getUser() - * - * @final - */ - protected function getUser() - { - if (!$this->container->has('security.token_storage')) { - throw new \LogicException('The SecurityBundle is not registered in your application. Try running "composer require symfony/security-bundle".'); - } - - if (null === $token = $this->container->get('security.token_storage')->getToken()) { - return null; - } - - if (!\is_object($user = $token->getUser())) { - // e.g. anonymous authentication - return null; - } - - return $user; - } - - /** - * Checks the validity of a CSRF token. - * - * @param string $id The id used when generating the token - * @param string|null $token The actual token sent with the request that should be validated - * - * @final - */ - protected function isCsrfTokenValid(string $id, ?string $token): bool - { - if (!$this->container->has('security.csrf.token_manager')) { - throw new \LogicException('CSRF protection is not enabled in your application. Enable it with the "csrf_protection" key in "config/packages/framework.yaml".'); - } - - return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id, $token)); - } - - /** - * Dispatches a message to the bus. - * - * @param object|Envelope $message The message or the message pre-wrapped in an envelope - * @param StampInterface[] $stamps - * - * @final - */ - protected function dispatchMessage($message, array $stamps = []): Envelope - { - if (!$this->container->has('messenger.default_bus')) { - $message = class_exists(Envelope::class) ? 'You need to define the "messenger.default_bus" configuration option.' : 'Try running "composer require symfony/messenger".'; - throw new \LogicException('The message bus is not enabled in your application. '.$message); - } - - return $this->container->get('messenger.default_bus')->dispatch($message, $stamps); - } - - /** - * Adds a Link HTTP header to the current response. - * - * @see https://tools.ietf.org/html/rfc5988 - * - * @final - */ - protected function addLink(Request $request, LinkInterface $link) - { - if (!class_exists(AddLinkHeaderListener::class)) { - throw new \LogicException('You can not use the "addLink" method if the WebLink component is not available. Try running "composer require symfony/web-link".'); - } - - if (null === $linkProvider = $request->attributes->get('_links')) { - $request->attributes->set('_links', new GenericLinkProvider([$link])); - - return; - } - - $request->attributes->set('_links', $linkProvider->withLink($link)); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Controller/TemplateController.php b/src/Symfony/Bundle/FrameworkBundle/Controller/TemplateController.php index 8e359569f8ced..0fff40bac58ea 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Controller/TemplateController.php +++ b/src/Symfony/Bundle/FrameworkBundle/Controller/TemplateController.php @@ -12,7 +12,6 @@ namespace Symfony\Bundle\FrameworkBundle\Controller; use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\Templating\EngineInterface; use Twig\Environment; /** @@ -25,16 +24,10 @@ class TemplateController { private $twig; - private $templating; - public function __construct(Environment $twig = null, EngineInterface $templating = null) + public function __construct(Environment $twig = null) { - if (null !== $templating) { - @trigger_error(sprintf('Using a "%s" instance for "%s" is deprecated since version 4.4; use a \Twig\Environment instance instead.', EngineInterface::class, __CLASS__), E_USER_DEPRECATED); - } - $this->twig = $twig; - $this->templating = $templating; } /** @@ -47,14 +40,12 @@ public function __construct(Environment $twig = null, EngineInterface $templatin */ public function templateAction(string $template, int $maxAge = null, int $sharedAge = null, bool $private = null): Response { - if ($this->templating) { - $response = new Response($this->templating->render($template)); - } elseif ($this->twig) { - $response = new Response($this->twig->render($template)); - } else { - throw new \LogicException('You can not use the TemplateController if the Templating Component or the Twig Bundle are not available.'); + if (null === $this->twig) { + throw new \LogicException('You can not use the TemplateController if the Twig Bundle is not available.'); } + $response = new Response($this->twig->render($template)); + if ($maxAge) { $response->setMaxAge($maxAge); } diff --git a/src/Symfony/Bundle/FrameworkBundle/DataCollector/RequestDataCollector.php b/src/Symfony/Bundle/FrameworkBundle/DataCollector/RequestDataCollector.php deleted file mode 100644 index 3e82f27e2c585..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/DataCollector/RequestDataCollector.php +++ /dev/null @@ -1,27 +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\DataCollector; - -use Symfony\Component\HttpKernel\DataCollector\RequestDataCollector as BaseRequestDataCollector; - -@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.1. Use %s instead.', RequestDataCollector::class, BaseRequestDataCollector::class), E_USER_DEPRECATED); - -/** - * RequestDataCollector. - * - * @author Jules Pietri - * - * @deprecated since Symfony 4.1 - */ -class RequestDataCollector extends BaseRequestDataCollector -{ -} diff --git a/src/Symfony/Bundle/FrameworkBundle/DataCollector/RouterDataCollector.php b/src/Symfony/Bundle/FrameworkBundle/DataCollector/RouterDataCollector.php index 58fcc68e8e84c..0acdc61a3db18 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DataCollector/RouterDataCollector.php +++ b/src/Symfony/Bundle/FrameworkBundle/DataCollector/RouterDataCollector.php @@ -20,7 +20,7 @@ * * @author Fabien Potencier * - * @final since Symfony 4.4 + * @final */ class RouterDataCollector extends BaseRouterDataCollector { diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/CompatibilityServiceSubscriberInterface.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/CompatibilityServiceSubscriberInterface.php deleted file mode 100644 index 41d4aa81e99c1..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/CompatibilityServiceSubscriberInterface.php +++ /dev/null @@ -1,31 +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\DependencyInjection; - -use Symfony\Component\DependencyInjection\ServiceSubscriberInterface as LegacyServiceSubscriberInterface; -use Symfony\Contracts\Service\ServiceSubscriberInterface; - -if (interface_exists(LegacyServiceSubscriberInterface::class)) { - /** - * @internal - */ - interface CompatibilityServiceSubscriberInterface extends LegacyServiceSubscriberInterface - { - } -} else { - /** - * @internal - */ - interface CompatibilityServiceSubscriberInterface extends ServiceSubscriberInterface - { - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddExpressionLanguageProvidersPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddExpressionLanguageProvidersPass.php index 7c6c85f64b2b9..47195b48300f4 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddExpressionLanguageProvidersPass.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/AddExpressionLanguageProvidersPass.php @@ -11,7 +11,6 @@ namespace Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler; -use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddExpressionLanguageProvidersPass as SecurityExpressionLanguageProvidersPass; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; @@ -23,17 +22,6 @@ */ class AddExpressionLanguageProvidersPass implements CompilerPassInterface { - private $handleSecurityLanguageProviders; - - public function __construct(bool $handleSecurityLanguageProviders = true) - { - if ($handleSecurityLanguageProviders) { - @trigger_error(sprintf('Registering services tagged "security.expression_language_provider" with "%s" is deprecated since Symfony 4.2, use the "%s" instead.', __CLASS__, SecurityExpressionLanguageProvidersPass::class), E_USER_DEPRECATED); - } - - $this->handleSecurityLanguageProviders = $handleSecurityLanguageProviders; - } - /** * {@inheritdoc} */ @@ -46,13 +34,5 @@ public function process(ContainerBuilder $container) $definition->addMethodCall('addExpressionLanguageProvider', [new Reference($id)]); } } - - // security - if ($this->handleSecurityLanguageProviders && $container->has('security.expression_language')) { - $definition = $container->findDefinition('security.expression_language'); - foreach ($container->findTaggedServiceIds('security.expression_language_provider', true) as $id => $attributes) { - $definition->addMethodCall('registerProvider', [new Reference($id)]); - } - } } } diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CacheCollectorPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CacheCollectorPass.php deleted file mode 100644 index 7be7464f710de..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CacheCollectorPass.php +++ /dev/null @@ -1,27 +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\DependencyInjection\Compiler; - -use Symfony\Component\Cache\DependencyInjection\CacheCollectorPass as BaseCacheCollectorPass; - -@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use "%s" instead.', CacheCollectorPass::class, BaseCacheCollectorPass::class), E_USER_DEPRECATED); - -/** - * Inject a data collector to all the cache services to be able to get detailed statistics. - * - * @author Tobias Nyholm - * - * @deprecated since Symfony 4.2, use Symfony\Component\Cache\DependencyInjection\CacheCollectorPass instead. - */ -class CacheCollectorPass extends BaseCacheCollectorPass -{ -} diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CachePoolClearerPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CachePoolClearerPass.php deleted file mode 100644 index c43cb769dbf9c..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CachePoolClearerPass.php +++ /dev/null @@ -1,25 +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\DependencyInjection\Compiler; - -use Symfony\Component\Cache\DependencyInjection\CachePoolClearerPass as BaseCachePoolClearerPass; - -@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use "%s" instead.', CachePoolClearerPass::class, BaseCachePoolClearerPass::class), E_USER_DEPRECATED); - -/** - * @author Nicolas Grekas - * - * @deprecated since version 4.2, use Symfony\Component\Cache\DependencyInjection\CachePoolClearerPass instead. - */ -class CachePoolClearerPass extends BaseCachePoolClearerPass -{ -} diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CachePoolPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CachePoolPass.php deleted file mode 100644 index bc7ab8bcc140a..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CachePoolPass.php +++ /dev/null @@ -1,25 +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\DependencyInjection\Compiler; - -use Symfony\Component\Cache\DependencyInjection\CachePoolPass as BaseCachePoolPass; - -@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use "%s" instead.', CachePoolPass::class, BaseCachePoolPass::class), E_USER_DEPRECATED); - -/** - * @author Nicolas Grekas - * - * @deprecated since version 4.2, use Symfony\Component\Cache\DependencyInjection\CachePoolPass instead. - */ -class CachePoolPass extends BaseCachePoolPass -{ -} diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CachePoolPrunerPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CachePoolPrunerPass.php deleted file mode 100644 index d20c93a024a7c..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/CachePoolPrunerPass.php +++ /dev/null @@ -1,25 +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\DependencyInjection\Compiler; - -use Symfony\Component\Cache\DependencyInjection\CachePoolPrunerPass as BaseCachePoolPrunerPass; - -@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use "%s" instead.', CachePoolPrunerPass::class, BaseCachePoolPrunerPass::class), E_USER_DEPRECATED); - -/** - * @author Rob Frawley 2nd - * - * @deprecated since Symfony 4.2, use Symfony\Component\Cache\DependencyInjection\CachePoolPrunerPass instead. - */ -class CachePoolPrunerPass extends BaseCachePoolPrunerPass -{ -} diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/TemplatingPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/TemplatingPass.php deleted file mode 100644 index be7418d909726..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/TemplatingPass.php +++ /dev/null @@ -1,62 +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\DependencyInjection\Compiler; - -use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface as FrameworkBundleEngineInterface; -use Symfony\Component\DependencyInjection\Alias; -use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\Templating\EngineInterface as ComponentEngineInterface; - -/** - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class TemplatingPass implements CompilerPassInterface -{ - public function process(ContainerBuilder $container) - { - if ($container->hasDefinition('templating')) { - return; - } - - if ($container->hasAlias('templating')) { - $container->setAlias(ComponentEngineInterface::class, new Alias('templating', false)); - $container->setAlias(FrameworkBundleEngineInterface::class, new Alias('templating', false)); - } - - if ($container->hasDefinition('templating.engine.php')) { - $refs = []; - $helpers = []; - - foreach ($container->findTaggedServiceIds('templating.helper', true) as $id => $attributes) { - if (!$container->getDefinition($id)->isDeprecated()) { - @trigger_error('The "templating.helper" tag is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - } - - if (isset($attributes[0]['alias'])) { - $helpers[$attributes[0]['alias']] = $id; - $refs[$id] = new Reference($id); - } - } - - if (\count($helpers) > 0) { - $definition = $container->getDefinition('templating.engine.php'); - $definition->addMethodCall('setHelpers', [$helpers]); - - if ($container->hasDefinition('templating.engine.php.helpers_locator')) { - $container->getDefinition('templating.engine.php.helpers_locator')->replaceArgument(0, $refs); - } - } - } - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/UnusedTagsPass.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/UnusedTagsPass.php index e21550115b295..5bbcb7452e73d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/UnusedTagsPass.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Compiler/UnusedTagsPass.php @@ -56,7 +56,6 @@ class UnusedTagsPass implements CompilerPassInterface 'security.voter', 'serializer.encoder', 'serializer.normalizer', - 'templating.helper', 'translation.dumper', 'translation.extractor', 'translation.loader', diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php index c99106299a588..952079cd17303 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/Configuration.php @@ -27,6 +27,7 @@ use Symfony\Component\Lock\Store\SemaphoreStore; use Symfony\Component\Mailer\Mailer; use Symfony\Component\Messenger\MessageBusInterface; +use Symfony\Component\Notifier\Notifier; use Symfony\Component\PropertyInfo\PropertyInfoExtractorInterface; use Symfony\Component\Serializer\Serializer; use Symfony\Component\Translation\Translator; @@ -99,7 +100,6 @@ public function getConfigTreeBuilder() $this->addRouterSection($rootNode); $this->addSessionSection($rootNode); $this->addRequestSection($rootNode); - $this->addTemplatingSection($rootNode); $this->addAssetsSection($rootNode); $this->addTranslatorSection($rootNode); $this->addValidationSection($rootNode); @@ -116,6 +116,7 @@ public function getConfigTreeBuilder() $this->addHttpClientSection($rootNode); $this->addMailerSection($rootNode); $this->addSecretsSection($rootNode); + $this->addNotifierSection($rootNode); return $treeBuilder; } @@ -277,15 +278,6 @@ private function addWorkflowSection(ArrayNodeDefinition $rootNode) ->arrayNode('workflows') ->useAttributeAsKey('name') ->prototype('array') - ->beforeNormalization() - ->always(function ($v) { - if (isset($v['initial_place'])) { - $v['initial_marking'] = [$v['initial_place']]; - } - - return $v; - }) - ->end() ->fixXmlConfig('support') ->fixXmlConfig('place') ->fixXmlConfig('transition') @@ -298,44 +290,17 @@ private function addWorkflowSection(ArrayNodeDefinition $rootNode) ->defaultValue('state_machine') ->end() ->arrayNode('marking_store') - ->fixXmlConfig('argument') ->children() ->enumNode('type') - ->values(['multiple_state', 'single_state', 'method']) - ->validate() - ->ifTrue(function ($v) { return 'method' !== $v; }) - ->then(function ($v) { - @trigger_error('Passing something else than "method" has been deprecated in Symfony 4.3.', E_USER_DEPRECATED); - - return $v; - }) - ->end() - ->end() - ->arrayNode('arguments') - ->setDeprecated('The "%path%.%node%" configuration key has been deprecated in Symfony 4.3. Use "property" instead.') - ->beforeNormalization() - ->ifString() - ->then(function ($v) { return [$v]; }) - ->end() - ->requiresAtLeastOneElement() - ->prototype('scalar') - ->end() + ->values(['method']) ->end() ->scalarNode('property') - ->defaultNull() // In Symfony 5.0, set "marking" as default property + ->defaultValue('marking') ->end() ->scalarNode('service') ->cannotBeEmpty() ->end() ->end() - ->validate() - ->ifTrue(function ($v) { return isset($v['type']) && isset($v['service']); }) - ->thenInvalid('"type" and "service" cannot be used together.') - ->end() - ->validate() - ->ifTrue(function ($v) { return !empty($v['arguments']) && isset($v['service']); }) - ->thenInvalid('"arguments" and "service" cannot be used together.') - ->end() ->end() ->arrayNode('supports') ->beforeNormalization() @@ -353,10 +318,6 @@ private function addWorkflowSection(ArrayNodeDefinition $rootNode) ->scalarNode('support_strategy') ->cannotBeEmpty() ->end() - ->scalarNode('initial_place') - ->setDeprecated('The "%path%.%node%" configuration key has been deprecated in Symfony 4.3, use the "initial_marking" configuration key instead.') - ->defaultNull() - ->end() ->arrayNode('initial_marking') ->beforeNormalization()->castToArray()->end() ->defaultValue([]) @@ -490,24 +451,6 @@ private function addWorkflowSection(ArrayNodeDefinition $rootNode) }) ->thenInvalid('"supports" or "support_strategy" should be configured.') ->end() - ->validate() - ->ifTrue(function ($v) { - return 'workflow' === $v['type'] && 'single_state' === ($v['marking_store']['type'] ?? false); - }) - ->then(function ($v) { - @trigger_error('Using a workflow with type=workflow and a marking_store=single_state is deprecated since Symfony 4.3. Use type=state_machine instead.', E_USER_DEPRECATED); - - return $v; - }) - ->end() - ->validate() - ->ifTrue(function ($v) { - return isset($v['marking_store']['property']) - && (!isset($v['marking_store']['type']) || 'method' !== $v['marking_store']['type']) - ; - }) - ->thenInvalid('"property" option is only supported by the "method" marking store.') - ->end() ->end() ->end() ->end() @@ -619,64 +562,6 @@ private function addRequestSection(ArrayNodeDefinition $rootNode) ; } - private function addTemplatingSection(ArrayNodeDefinition $rootNode) - { - $rootNode - ->children() - ->arrayNode('templating') - ->info('templating configuration') - ->canBeEnabled() - ->setDeprecated('The "%path%.%node%" configuration is deprecated since Symfony 4.3. Configure the "twig" section provided by the Twig Bundle instead.') - ->beforeNormalization() - ->ifTrue(function ($v) { return false === $v || \is_array($v) && false === $v['enabled']; }) - ->then(function () { return ['enabled' => false, 'engines' => false]; }) - ->end() - ->children() - ->scalarNode('hinclude_default_template')->setDeprecated('Setting "templating.hinclude_default_template" is deprecated since Symfony 4.3, use "fragments.hinclude_default_template" instead.')->defaultNull()->end() - ->scalarNode('cache')->end() - ->arrayNode('form') - ->addDefaultsIfNotSet() - ->fixXmlConfig('resource') - ->children() - ->arrayNode('resources') - ->addDefaultChildrenIfNoneSet() - ->prototype('scalar')->defaultValue('FrameworkBundle:Form')->end() - ->validate() - ->ifTrue(function ($v) {return !\in_array('FrameworkBundle:Form', $v); }) - ->then(function ($v) { - return array_merge(['FrameworkBundle:Form'], $v); - }) - ->end() - ->end() - ->end() - ->end() - ->end() - ->fixXmlConfig('engine') - ->children() - ->arrayNode('engines') - ->example(['twig']) - ->isRequired() - ->requiresAtLeastOneElement() - ->canBeUnset() - ->beforeNormalization() - ->ifTrue(function ($v) { return !\is_array($v) && false !== $v; }) - ->then(function ($v) { return [$v]; }) - ->end() - ->prototype('scalar')->end() - ->end() - ->end() - ->fixXmlConfig('loader') - ->children() - ->arrayNode('loaders') - ->beforeNormalization()->castToArray()->end() - ->prototype('scalar')->end() - ->end() - ->end() - ->end() - ->end() - ; - } - private function addAssetsSection(ArrayNodeDefinition $rootNode) { $rootNode @@ -804,27 +689,6 @@ private function addValidationSection(ArrayNodeDefinition $rootNode) ->arrayNode('validation') ->info('validation configuration') ->{!class_exists(FullStack::class) && class_exists(Validation::class) ? 'canBeDisabled' : 'canBeEnabled'}() - ->validate() - ->ifTrue(function ($v) { return isset($v['strict_email']) && isset($v['email_validation_mode']); }) - ->thenInvalid('"strict_email" and "email_validation_mode" cannot be used together.') - ->end() - ->beforeNormalization() - ->ifTrue(function ($v) { return isset($v['strict_email']); }) - ->then(function ($v) { - @trigger_error('The "framework.validation.strict_email" configuration key has been deprecated in Symfony 4.1. Use the "framework.validation.email_validation_mode" configuration key instead.', E_USER_DEPRECATED); - - return $v; - }) - ->end() - ->beforeNormalization() - ->ifTrue(function ($v) { return isset($v['strict_email']) && !isset($v['email_validation_mode']); }) - ->then(function ($v) { - $v['email_validation_mode'] = $v['strict_email'] ? 'strict' : 'loose'; - unset($v['strict_email']); - - return $v; - }) - ->end() ->children() ->scalarNode('cache')->end() ->booleanNode('enable_annotations')->{!class_exists(FullStack::class) && class_exists(Annotation::class) ? 'defaultTrue' : 'defaultFalse'}()->end() @@ -835,7 +699,6 @@ private function addValidationSection(ArrayNodeDefinition $rootNode) ->validate()->castToArray()->end() ->end() ->scalarNode('translation_domain')->defaultValue('validators')->end() - ->booleanNode('strict_email')->end() ->enumNode('email_validation_mode')->values(['html5', 'loose', 'strict'])->end() ->arrayNode('mapping') ->addDefaultsIfNotSet() @@ -1632,4 +1495,53 @@ private function addMailerSection(ArrayNodeDefinition $rootNode) ->end() ; } + + private function addNotifierSection(ArrayNodeDefinition $rootNode) + { + $rootNode + ->children() + ->arrayNode('notifier') + ->info('Notifier configuration') + ->{!class_exists(FullStack::class) && class_exists(Notifier::class) ? 'canBeDisabled' : 'canBeEnabled'}() + ->fixXmlConfig('chatter_transport') + ->children() + ->arrayNode('chatter_transports') + ->useAttributeAsKey('name') + ->prototype('scalar')->end() + ->end() + ->end() + ->fixXmlConfig('texter_transport') + ->children() + ->arrayNode('texter_transports') + ->useAttributeAsKey('name') + ->prototype('scalar')->end() + ->end() + ->end() + ->children() + ->booleanNode('notification_on_failed_messages')->defaultFalse()->end() + ->end() + ->children() + ->arrayNode('channel_policy') + ->useAttributeAsKey('name') + ->prototype('array') + ->beforeNormalization()->ifString()->then(function (string $v) { return [$v]; })->end() + ->prototype('scalar')->end() + ->end() + ->end() + ->end() + ->fixXmlConfig('admin_recipient') + ->children() + ->arrayNode('admin_recipients') + ->prototype('array') + ->children() + ->scalarNode('email')->cannotBeEmpty()->end() + ->scalarNode('phone')->defaultValue('')->end() + ->end() + ->end() + ->end() + ->end() + ->end() + ->end() + ; + } } diff --git a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php index a56a05e741241..9f8f78bf36570 100644 --- a/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php +++ b/src/Symfony/Bundle/FrameworkBundle/DependencyInjection/FrameworkExtension.php @@ -23,7 +23,6 @@ use Symfony\Bridge\Twig\Extension\CsrfExtension; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Bundle\FrameworkBundle\Routing\AnnotatedRouteControllerLoader; -use Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher; use Symfony\Bundle\FrameworkBundle\Routing\RouteLoaderInterface; use Symfony\Bundle\FullStack; use Symfony\Component\Asset\PackageInterface; @@ -70,13 +69,11 @@ use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface; use Symfony\Component\HttpKernel\DataCollector\DataCollectorInterface; use Symfony\Component\HttpKernel\DependencyInjection\Extension; -use Symfony\Component\Lock\Factory; use Symfony\Component\Lock\Lock; use Symfony\Component\Lock\LockFactory; use Symfony\Component\Lock\LockInterface; use Symfony\Component\Lock\PersistingStoreInterface; use Symfony\Component\Lock\Store\StoreFactory; -use Symfony\Component\Lock\StoreInterface; use Symfony\Component\Mailer\Bridge\Amazon\Transport\SesTransportFactory; use Symfony\Component\Mailer\Bridge\Google\Transport\GmailTransportFactory; use Symfony\Component\Mailer\Bridge\Mailchimp\Transport\MandrillTransportFactory; @@ -91,6 +88,12 @@ use Symfony\Component\Messenger\Transport\TransportInterface; use Symfony\Component\Mime\MimeTypeGuesserInterface; use Symfony\Component\Mime\MimeTypes; +use Symfony\Component\Notifier\Bridge\Nexmo\NexmoTransportFactory; +use Symfony\Component\Notifier\Bridge\Slack\SlackTransportFactory; +use Symfony\Component\Notifier\Bridge\Telegram\TelegramTransportFactory; +use Symfony\Component\Notifier\Bridge\Twilio\TwilioTransportFactory; +use Symfony\Component\Notifier\Notifier; +use Symfony\Component\Notifier\Recipient\AdminRecipient; use Symfony\Component\PropertyAccess\PropertyAccessor; use Symfony\Component\PropertyInfo\PropertyAccessExtractorInterface; use Symfony\Component\PropertyInfo\PropertyDescriptionExtractorInterface; @@ -98,28 +101,21 @@ use Symfony\Component\PropertyInfo\PropertyInitializableExtractorInterface; use Symfony\Component\PropertyInfo\PropertyListExtractorInterface; use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface; -use Symfony\Component\Routing\Generator\Dumper\PhpGeneratorDumper; -use Symfony\Component\Routing\Generator\UrlGenerator; use Symfony\Component\Routing\Loader\AnnotationDirectoryLoader; use Symfony\Component\Routing\Loader\AnnotationFileLoader; -use Symfony\Component\Routing\Matcher\CompiledUrlMatcher; -use Symfony\Component\Routing\Matcher\Dumper\PhpMatcherDumper; use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface; use Symfony\Component\Serializer\Encoder\DecoderInterface; use Symfony\Component\Serializer\Encoder\EncoderInterface; -use Symfony\Component\Serializer\Mapping\ClassDiscriminatorFromClassMetadata; -use Symfony\Component\Serializer\Normalizer\ConstraintViolationListNormalizer; use Symfony\Component\Serializer\Normalizer\DenormalizerInterface; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; use Symfony\Component\Stopwatch\Stopwatch; +use Symfony\Component\String\Slugger\SluggerInterface; use Symfony\Component\Translation\Command\XliffLintCommand as BaseXliffLintCommand; use Symfony\Component\Translation\Translator; -use Symfony\Component\Translation\TranslatorInterface; use Symfony\Component\Validator\ConstraintValidatorInterface; use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader; use Symfony\Component\Validator\ObjectInitializerInterface; -use Symfony\Component\Validator\Util\LegacyTranslatorProxy; use Symfony\Component\WebLink\HttpHeaderSerializer; use Symfony\Component\Workflow; use Symfony\Component\Workflow\WorkflowInterface; @@ -204,6 +200,21 @@ public function load(array $configs, ContainerBuilder $container) } } + // If the slugger is used but the String component is not available, we should throw an error + if (!interface_exists(SluggerInterface::class)) { + $container->register('slugger', 'stdClass') + ->addError('You cannot use the "slugger" service since the String component is not installed. Try running "composer require symfony/string".'); + } else { + if (!interface_exists(LocaleAwareInterface::class)) { + $container->register('slugger', 'stdClass') + ->addError('You cannot use the "slugger" service since the Translation contracts are not installed. Try running "composer require symfony/translation".'); + } + + if (!\extension_loaded('intl') && !\defined('PHPUNIT_COMPOSER_INSTALL')) { + @trigger_error('Please install the "intl" PHP extension for best performance.', E_USER_DEPRECATED); + } + } + if (isset($config['secret'])) { $container->setParameter('kernel.secret', $config['secret']); } @@ -214,23 +225,20 @@ public function load(array $configs, ContainerBuilder $container) $container->setParameter('kernel.error_controller', $config['error_controller']); if (!$container->hasParameter('debug.file_link_format')) { - if (!$container->hasParameter('templating.helper.code.file_link_format')) { - $links = [ - 'textmate' => 'txmt://open?url=file://%%f&line=%%l', - 'macvim' => 'mvim://open?url=file://%%f&line=%%l', - 'emacs' => 'emacs://open?url=file://%%f&line=%%l', - 'sublime' => 'subl://open?url=file://%%f&line=%%l', - 'phpstorm' => 'phpstorm://open?file=%%f&line=%%l', - 'atom' => 'atom://core/open/file?filename=%%f&line=%%l', - 'vscode' => 'vscode://file/%%f:%%l', - ]; - $ide = $config['ide']; - // mark any env vars found in the ide setting as used - $container->resolveEnvPlaceholders($ide); + $links = [ + 'textmate' => 'txmt://open?url=file://%%f&line=%%l', + 'macvim' => 'mvim://open?url=file://%%f&line=%%l', + 'emacs' => 'emacs://open?url=file://%%f&line=%%l', + 'sublime' => 'subl://open?url=file://%%f&line=%%l', + 'phpstorm' => 'phpstorm://open?file=%%f&line=%%l', + 'atom' => 'atom://core/open/file?filename=%%f&line=%%l', + 'vscode' => 'vscode://file/%%f:%%l', + ]; + $ide = $config['ide']; + // mark any env vars found in the ide setting as used + $container->resolveEnvPlaceholders($ide); - $container->setParameter('templating.helper.code.file_link_format', str_replace('%', '%%', ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format')) ?: (isset($links[$ide]) ? $links[$ide] : $ide)); - } - $container->setParameter('debug.file_link_format', '%templating.helper.code.file_link_format%'); + $container->setParameter('debug.file_link_format', str_replace('%', '%%', ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format')) ?: (isset($links[$ide]) ? $links[$ide] : $ide)); } if (!empty($config['test'])) { @@ -293,16 +301,6 @@ public function load(array $configs, ContainerBuilder $container) $this->registerAssetsConfiguration($config['assets'], $container, $loader); } - if ($this->isConfigEnabled($container, $config['templating'])) { - @trigger_error('Enabling the Templating component is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - - if (!class_exists('Symfony\Component\Templating\PhpEngine')) { - throw new LogicException('Templating support cannot be enabled as the Templating component is not installed. Try running "composer require symfony/templating".'); - } - - $this->registerTemplatingConfiguration($config['templating'], $container, $loader); - } - if ($this->messengerConfigEnabled = $this->isConfigEnabled($container, $config['messenger'])) { $this->registerMessengerConfiguration($config['messenger'], $container, $loader, $config['serializer'], $config['validation']); } else { @@ -323,6 +321,10 @@ public function load(array $configs, ContainerBuilder $container) $this->registerMailerConfiguration($config['mailer'], $container, $loader); } + if ($this->isConfigEnabled($container, $config['notifier'])) { + $this->registerNotifierConfiguration($config['notifier'], $container, $loader); + } + $propertyInfoEnabled = $this->isConfigEnabled($container, $config['property_info']); $this->registerValidationConfiguration($config['validation'], $container, $loader, $propertyInfoEnabled); $this->registerEsiConfiguration($config['esi'], $container, $loader); @@ -523,9 +525,6 @@ private function registerFragmentsConfiguration(array $config, ContainerBuilder return; } - if ($container->hasParameter('fragment.renderer.hinclude.global_template') && null !== $container->getParameter('fragment.renderer.hinclude.global_template') && null !== $config['hinclude_default_template']) { - throw new \LogicException('You cannot set both "templating.hinclude_default_template" and "fragments.hinclude_default_template", please only use "fragments.hinclude_default_template".'); - } $container->setParameter('fragment.renderer.hinclude.global_template', $config['hinclude_default_template']); @@ -680,7 +679,7 @@ private function registerWorkflowConfiguration(array $config, ContainerBuilder $ // Create places $places = array_column($workflow['places'], 'name'); - $initialMarking = $workflow['initial_marking'] ?? $workflow['initial_place'] ?? []; + $initialMarking = $workflow['initial_marking'] ?? []; // Create a Definition $definitionDefinition = new Definition(Workflow\Definition::class); @@ -696,17 +695,11 @@ private function registerWorkflowConfiguration(array $config, ContainerBuilder $ // Create MarkingStore if (isset($workflow['marking_store']['type'])) { - $markingStoreDefinition = new ChildDefinition('workflow.marking_store.'.$workflow['marking_store']['type']); - if ('method' === $workflow['marking_store']['type']) { - $markingStoreDefinition->setArguments([ - 'state_machine' === $type, //single state - $workflow['marking_store']['property'] ?? 'marking', - ]); - } else { - foreach ($workflow['marking_store']['arguments'] as $argument) { - $markingStoreDefinition->addArgument($argument); - } - } + $markingStoreDefinition = new ChildDefinition('workflow.marking_store.method'); + $markingStoreDefinition->setArguments([ + 'state_machine' === $type, //single state + $workflow['marking_store']['property'], + ]); } elseif (isset($workflow['marking_store']['service'])) { $markingStoreDefinition = new Reference($workflow['marking_store']['service']); } @@ -725,27 +718,18 @@ private function registerWorkflowConfiguration(array $config, ContainerBuilder $ $container->registerAliasForArgument($workflowId, WorkflowInterface::class, $name.'.'.$type); // Validate Workflow - $validator = null; - switch (true) { - case 'state_machine' === $workflow['type']: - $validator = new Workflow\Validator\StateMachineValidator(); - break; - case 'single_state' === ($workflow['marking_store']['type'] ?? null): - $validator = new Workflow\Validator\WorkflowValidator(true); - break; - case 'multiple_state' === ($workflow['marking_store']['type'] ?? false): - $validator = new Workflow\Validator\WorkflowValidator(false); - break; - } - - if ($validator) { - $trs = array_map(function (Reference $ref) use ($container): Workflow\Transition { - return $container->get((string) $ref); - }, $transitions); - $realDefinition = new Workflow\Definition($places, $trs, $initialMarking); - $validator->validate($realDefinition, $name); + if ('state_machine' === $workflow['type']) { + $validator = new Workflow\Validator\StateMachineValidator(); + } else { + $validator = new Workflow\Validator\WorkflowValidator(); } + $trs = array_map(function (Reference $ref) use ($container): Workflow\Transition { + return $container->get((string) $ref); + }, $transitions); + $realDefinition = new Workflow\Definition($places, $trs, $initialMarking); + $validator->validate($realDefinition, $name); + // Add workflow to Registry if ($workflow['supports']) { foreach ($workflow['supports'] as $supportedClassName) { @@ -855,23 +839,16 @@ private function registerRouterConfiguration(array $config, ContainerBuilder $co $loader->load('routing.xml'); if ($config['utf8']) { - $container->getDefinition('routing.loader')->replaceArgument(2, ['utf8' => true]); + $container->getDefinition('routing.loader')->replaceArgument(1, ['utf8' => true]); } $container->setParameter('router.resource', $config['resource']); - $container->setParameter('router.cache_class_prefix', $container->getParameter('kernel.container_class')); // deprecated $router = $container->findDefinition('router.default'); $argument = $router->getArgument(2); $argument['strict_requirements'] = $config['strict_requirements']; if (isset($config['type'])) { $argument['resource_type'] = $config['type']; } - if (!class_exists(CompiledUrlMatcher::class)) { - $argument['matcher_class'] = $argument['matcher_base_class'] = $argument['matcher_base_class'] ?? RedirectableUrlMatcher::class; - $argument['matcher_dumper_class'] = PhpMatcherDumper::class; - $argument['generator_class'] = $argument['generator_base_class'] = $argument['generator_base_class'] ?? UrlGenerator::class; - $argument['generator_dumper_class'] = PhpGeneratorDumper::class; - } $router->replaceArgument(2, $argument); $container->setParameter('request_listener.http_port', $config['http_port']); @@ -959,85 +936,6 @@ private function registerRequestConfiguration(array $config, ContainerBuilder $c } } - private function registerTemplatingConfiguration(array $config, ContainerBuilder $container, XmlFileLoader $loader) - { - $loader->load('templating.xml'); - - $container->setParameter('fragment.renderer.hinclude.global_template', $config['hinclude_default_template']); - - if ($container->getParameter('kernel.debug')) { - $logger = new Reference('logger', ContainerInterface::IGNORE_ON_INVALID_REFERENCE); - - $container->getDefinition('templating.loader.cache') - ->addTag('monolog.logger', ['channel' => 'templating']) - ->addMethodCall('setLogger', [$logger]); - $container->getDefinition('templating.loader.chain') - ->addTag('monolog.logger', ['channel' => 'templating']) - ->addMethodCall('setLogger', [$logger]); - } - - if (!empty($config['loaders'])) { - $loaders = array_map(function ($loader) { return new Reference($loader); }, $config['loaders']); - - // Use a delegation unless only a single loader was registered - if (1 === \count($loaders)) { - $container->setAlias('templating.loader', (string) reset($loaders))->setPrivate(true); - } else { - $container->getDefinition('templating.loader.chain')->addArgument($loaders); - $container->setAlias('templating.loader', 'templating.loader.chain')->setPrivate(true); - } - } - - $container->setParameter('templating.loader.cache.path', null); - if (isset($config['cache'])) { - // Wrap the existing loader with cache (must happen after loaders are registered) - $container->setDefinition('templating.loader.wrapped', $container->findDefinition('templating.loader')); - $loaderCache = $container->getDefinition('templating.loader.cache'); - $container->setParameter('templating.loader.cache.path', $config['cache']); - - $container->setDefinition('templating.loader', $loaderCache); - } - - $container->setParameter('templating.engines', $config['engines']); - $engines = array_map(function ($engine) { return new Reference('templating.engine.'.$engine); }, $config['engines']); - - // Use a delegation unless only a single engine was registered - if (1 === \count($engines)) { - $container->setAlias('templating', (string) reset($engines))->setPublic(true); - } else { - $templateEngineDefinition = $container->getDefinition('templating.engine.delegating'); - foreach ($engines as $engine) { - $templateEngineDefinition->addMethodCall('addEngine', [$engine]); - } - $container->setAlias('templating', 'templating.engine.delegating')->setPublic(true); - } - - $container->getDefinition('fragment.renderer.hinclude') - ->addTag('kernel.fragment_renderer', ['alias' => 'hinclude']) - ->replaceArgument(0, new Reference('templating')) - ; - - // configure the PHP engine if needed - if (\in_array('php', $config['engines'], true)) { - $loader->load('templating_php.xml'); - - $container->setParameter('templating.helper.form.resources', $config['form']['resources']); - - if ($container->getParameter('kernel.debug') && class_exists(Stopwatch::class)) { - $loader->load('templating_debug.xml'); - - $container->setDefinition('templating.engine.php', $container->findDefinition('debug.templating.engine.php')); - $container->setAlias('debug.templating.engine.php', 'templating.engine.php')->setPrivate(true); - } - - if ($container->has('assets.packages')) { - $container->getDefinition('templating.helper.assets')->replaceArgument(0, new Reference('assets.packages')); - } else { - $container->removeDefinition('templating.helper.assets'); - } - } - } - private function registerAssetsConfiguration(array $config, ContainerBuilder $container, XmlFileLoader $loader) { $loader->load('assets.xml'); @@ -1164,19 +1062,12 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder $dirs[] = $transPaths[] = \dirname($r->getFileName(), 2).'/Resources/translations'; } $defaultDir = $container->getParameterBag()->resolveValue($config['default_path']); - $rootDir = $container->getParameter('kernel.root_dir'); foreach ($container->getParameter('kernel.bundles_metadata') as $name => $bundle) { if ($container->fileExists($dir = $bundle['path'].'/Resources/translations') || $container->fileExists($dir = $bundle['path'].'/translations')) { $dirs[] = $dir; } else { $nonExistingDirs[] = $dir; } - if ($container->fileExists($dir = $rootDir.sprintf('/Resources/%s/translations', $name))) { - @trigger_error(sprintf('Translations directory "%s" is deprecated since Symfony 4.2, use "%s" instead.', $dir, $defaultDir), E_USER_DEPRECATED); - $dirs[] = $dir; - } else { - $nonExistingDirs[] = $dir; - } } foreach ($config['paths'] as $dir) { @@ -1201,16 +1092,6 @@ private function registerTranslatorConfiguration(array $config, ContainerBuilder $nonExistingDirs[] = $defaultDir; } - if ($container->fileExists($dir = $rootDir.'/Resources/translations')) { - if ($dir !== $defaultDir) { - @trigger_error(sprintf('Translations directory "%s" is deprecated since Symfony 4.2, use "%s" instead.', $dir, $defaultDir), E_USER_DEPRECATED); - } - - $dirs[] = $dir; - } else { - $nonExistingDirs[] = $dir; - } - // Register translation resources if ($dirs) { $files = []; @@ -1271,12 +1152,6 @@ private function registerValidationConfiguration(array $config, ContainerBuilder $validatorBuilder = $container->getDefinition('validator.builder'); - if (interface_exists(TranslatorInterface::class) && class_exists(LegacyTranslatorProxy::class)) { - $calls = $validatorBuilder->getMethodCalls(); - $calls[1] = ['setTranslator', [new Definition(LegacyTranslatorProxy::class, [new Reference('translator', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)])]]; - $validatorBuilder->setMethodCalls($calls); - } - $container->setParameter('validator.translation_domain', $config['translation_domain']); $files = ['xml' => [], 'yml' => []]; @@ -1519,15 +1394,6 @@ private function registerSerializerConfiguration(array $config, ContainerBuilder { $loader->load('serializer.xml'); - if (!class_exists(ConstraintViolationListNormalizer::class)) { - $container->removeDefinition('serializer.normalizer.constraint_violation_list'); - } - - if (!class_exists(ClassDiscriminatorFromClassMetadata::class)) { - $container->removeAlias('Symfony\Component\Serializer\Mapping\ClassDiscriminatorResolverInterface'); - $container->removeDefinition('serializer.mapping.class_discriminator_resolver'); - } - $chainLoader = $container->getDefinition('serializer.mapping.chain_loader'); if (!class_exists('Symfony\Component\PropertyAccess\PropertyAccessor')) { @@ -1681,15 +1547,11 @@ private function registerLockConfiguration(array $config, ContainerBuilder $cont $container->setAlias('lock.store', new Alias('lock.'.$resourceName.'.store', false)); $container->setAlias('lock.factory', new Alias('lock.'.$resourceName.'.factory', false)); $container->setAlias('lock', new Alias('lock.'.$resourceName, false)); - $container->setAlias(StoreInterface::class, new Alias('lock.store', false)); $container->setAlias(PersistingStoreInterface::class, new Alias('lock.store', false)); - $container->setAlias(Factory::class, new Alias('lock.factory', false)); $container->setAlias(LockFactory::class, new Alias('lock.factory', false)); $container->setAlias(LockInterface::class, new Alias('lock', false)); } else { - $container->registerAliasForArgument('lock.'.$resourceName.'.store', StoreInterface::class, $resourceName.'.lock.store'); $container->registerAliasForArgument('lock.'.$resourceName.'.store', PersistingStoreInterface::class, $resourceName.'.lock.store'); - $container->registerAliasForArgument('lock.'.$resourceName.'.factory', Factory::class, $resourceName.'.lock.factory'); $container->registerAliasForArgument('lock.'.$resourceName.'.factory', LockFactory::class, $resourceName.'.lock.factory'); $container->registerAliasForArgument('lock.'.$resourceName, LockInterface::class, $resourceName.'.lock'); } @@ -1750,7 +1612,6 @@ private function registerMessengerConfiguration(array $config, ContainerBuilder $container->register($busId, MessageBus::class)->addArgument([])->addTag('messenger.bus'); if ($busId === $config['default_bus']) { - $container->setAlias('message_bus', $busId)->setPublic(true)->setDeprecated(true, 'The "%alias_id%" service is deprecated, use the "messenger.default_bus" service instead.'); $container->setAlias('messenger.default_bus', $busId)->setPublic(true); $container->setAlias(MessageBusInterface::class, $busId); } else { @@ -2046,6 +1907,69 @@ private function registerMailerConfiguration(array $config, ContainerBuilder $co $envelopeListener->setArgument(1, $recipients); } + private function registerNotifierConfiguration(array $config, ContainerBuilder $container, XmlFileLoader $loader) + { + if (!class_exists(Notifier::class)) { + throw new LogicException('Notifier support cannot be enabled as the component is not installed. Try running "composer require symfony/notifier".'); + } + + $loader->load('notifier.xml'); + $loader->load('notifier_transports.xml'); + + if ($config['chatter_transports']) { + $container->getDefinition('chatter.transports')->setArgument(0, $config['chatter_transports']); + } else { + $container->removeDefinition('chatter'); + } + if ($config['texter_transports']) { + $container->getDefinition('texter.transports')->setArgument(0, $config['texter_transports']); + } else { + $container->removeDefinition('texter'); + } + + if ($this->mailerConfigEnabled) { + $sender = $container->getDefinition('mailer.envelope_listener')->getArgument(0); + $container->getDefinition('notifier.channel.email')->setArgument(2, $sender); + } else { + $container->removeDefinition('notifier.channel.email'); + } + + if ($this->messengerConfigEnabled) { + if ($config['notification_on_failed_messages']) { + $container->getDefinition('notifier.failed_message_listener')->addTag('kernel.event_subscriber'); + } + + // as we have a bus, the channels don't need the transports + $container->getDefinition('notifier.channel.chat')->setArgument(0, null); + $container->getDefinition('notifier.channel.email')->setArgument(0, null); + $container->getDefinition('notifier.channel.sms')->setArgument(0, null); + } + + $container->getDefinition('notifier.channel_policy')->setArgument(0, $config['channel_policy']); + + $classToServices = [ + SlackTransportFactory::class => 'notifier.transport_factory.slack', + TelegramTransportFactory::class => 'notifier.transport_factory.telegram', + NexmoTransportFactory::class => 'notifier.transport_factory.nexmo', + TwilioTransportFactory::class => 'notifier.transport_factory.twilio', + ]; + + foreach ($classToServices as $class => $service) { + if (!class_exists($class)) { + $container->removeDefinition($service); + } + } + + if (isset($config['admin_recipients'])) { + $notifier = $container->getDefinition('notifier'); + foreach ($config['admin_recipients'] as $i => $recipient) { + $id = 'notifier.admin_recipient.'.$i; + $container->setDefinition($id, new Definition(AdminRecipient::class, [$recipient['email'], $recipient['phone']])); + $notifier->addMethodCall('addAdminRecipient', [new Reference($id)]); + } + } + } + /** * {@inheritdoc} */ diff --git a/src/Symfony/Bundle/FrameworkBundle/EventListener/ResolveControllerNameSubscriber.php b/src/Symfony/Bundle/FrameworkBundle/EventListener/ResolveControllerNameSubscriber.php deleted file mode 100644 index 169c03277970f..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/EventListener/ResolveControllerNameSubscriber.php +++ /dev/null @@ -1,72 +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\EventListener; - -use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser; -use Symfony\Component\EventDispatcher\EventSubscriberInterface; -use Symfony\Component\HttpKernel\Event\RequestEvent; -use Symfony\Component\HttpKernel\KernelEvents; - -/** - * Guarantees that the _controller key is parsed into its final format. - * - * @author Ryan Weaver - * - * @method onKernelRequest(RequestEvent $event) - * - * @deprecated since Symfony 4.1 - */ -class ResolveControllerNameSubscriber implements EventSubscriberInterface -{ - private $parser; - - public function __construct(ControllerNameParser $parser, bool $triggerDeprecation = true) - { - if ($triggerDeprecation) { - @trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.1.', __CLASS__), E_USER_DEPRECATED); - } - - $this->parser = $parser; - } - - /** - * @internal - */ - public function resolveControllerName(...$args) - { - $this->onKernelRequest(...$args); - } - - public function __call(string $method, array $args) - { - if ('onKernelRequest' !== $method && 'onKernelRequest' !== strtolower($method)) { - throw new \Error(sprintf('Error: Call to undefined method %s::%s()', \get_class($this), $method)); - } - - $event = $args[0]; - - $controller = $event->getRequest()->attributes->get('_controller'); - if (\is_string($controller) && false === strpos($controller, '::') && 2 === substr_count($controller, ':')) { - // controller in the a:b:c notation then - $event->getRequest()->attributes->set('_controller', $parsedNotation = $this->parser->parse($controller, false)); - - @trigger_error(sprintf('Referencing controllers with %s is deprecated since Symfony 4.1, use "%s" instead.', $controller, $parsedNotation), E_USER_DEPRECATED); - } - } - - public static function getSubscribedEvents() - { - return [ - KernelEvents::REQUEST => ['resolveControllerName', 24], - ]; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php index ed85fa2ea7586..6cafc4399e31a 100644 --- a/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php +++ b/src/Symfony/Bundle/FrameworkBundle/FrameworkBundle.php @@ -18,7 +18,6 @@ use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\DataCollectorTranslatorPass; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\LoggingTranslatorPass; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\ProfilerPass; -use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TemplatingPass; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TestServiceContainerRealRefPass; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\TestServiceContainerWeakRefPass; use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\UnusedTagsPass; @@ -99,7 +98,6 @@ public function build(ContainerBuilder $container) // must be registered before removing private services as some might be listeners/subscribers // but as late as possible to get resolved parameters $container->addCompilerPass((new RegisterListenersPass())->setHotPathEvents($hotPathEvents), PassConfig::TYPE_BEFORE_REMOVING); - $container->addCompilerPass(new TemplatingPass()); $this->addCompilerPassIfExists($container, AddConstraintValidatorsPass::class); $container->addCompilerPass(new AddAnnotationsCachedReaderPass(), PassConfig::TYPE_AFTER_REMOVING, -255); $this->addCompilerPassIfExists($container, AddValidatorInitializersPass::class); diff --git a/src/Symfony/Bundle/FrameworkBundle/HttpCache/HttpCache.php b/src/Symfony/Bundle/FrameworkBundle/HttpCache/HttpCache.php index 66a8cd466efa5..037d0f067c36a 100644 --- a/src/Symfony/Bundle/FrameworkBundle/HttpCache/HttpCache.php +++ b/src/Symfony/Bundle/FrameworkBundle/HttpCache/HttpCache.php @@ -40,19 +40,14 @@ public function __construct(KernelInterface $kernel, string $cacheDir = null) } /** - * Forwards the Request to the backend and returns the Response. - * - * @param bool $raw Whether to catch exceptions or not - * @param Response $entry A Response instance (the stale entry if present, null otherwise) - * - * @return Response A Response instance + * {@inheritdoc} */ - protected function forward(Request $request, $raw = false, Response $entry = null) + protected function forward(Request $request, bool $catch = false, Response $entry = null) { $this->getKernel()->boot(); $this->getKernel()->getContainer()->set('cache', $this); - return parent::forward($request, $raw, $entry); + return parent::forward($request, $catch, $entry); } /** diff --git a/src/Symfony/Bundle/FrameworkBundle/Kernel/MicroKernelTrait.php b/src/Symfony/Bundle/FrameworkBundle/Kernel/MicroKernelTrait.php index 181ea8276a6df..df9e801bbc701 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Kernel/MicroKernelTrait.php +++ b/src/Symfony/Bundle/FrameworkBundle/Kernel/MicroKernelTrait.php @@ -14,6 +14,7 @@ use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; use Symfony\Component\Routing\RouteCollectionBuilder; /** @@ -29,8 +30,28 @@ trait MicroKernelTrait * * $routes->import('config/routing.yml'); * $routes->add('/admin', 'App\Controller\AdminController::dashboard', 'admin_dashboard'); + * + * @final since Symfony 5.1, override configureRouting() instead + * + * @internal since Symfony 5.1, use configureRouting() instead + */ + protected function configureRoutes(RouteCollectionBuilder $routes) + { + } + + /** + * Adds or imports routes into your application. + * + * $routes->import($this->getProjectDir().'/config/*.{yaml,php}'); + * $routes + * ->add('admin_dashboard', '/admin') + * ->controller('App\Controller\AdminController::dashboard') + * ; */ - abstract protected function configureRoutes(RouteCollectionBuilder $routes); + protected function configureRouting(RoutingConfigurator $routes): void + { + @trigger_error(sprintf('Not overriding the "%s()" method is deprecated since Symfony 5.1 and will trigger a fatal error in 6.0.', __METHOD__), E_USER_DEPRECATED); + } /** * Configures the container. @@ -91,7 +112,15 @@ public function loadRoutes(LoaderInterface $loader) { $routes = new RouteCollectionBuilder($loader); $this->configureRoutes($routes); + $collection = $routes->build(); + + if (0 !== \count($collection)) { + @trigger_error(sprintf('Adding routes via the "%s:configureRoutes()" method is deprecated since Symfony 5.1 and will have no effect in 6.0; use "configureRouting()" instead.', self::class), E_USER_DEPRECATED); + } + + $file = (new \ReflectionObject($this))->getFileName(); + $this->configureRouting(new RoutingConfigurator($collection, $loader, null, $file)); - return $routes->build(); + return $collection; } } diff --git a/src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php b/src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php index b05b60def12d1..38d2f06f2e282 100644 --- a/src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php +++ b/src/Symfony/Bundle/FrameworkBundle/KernelBrowser.php @@ -11,11 +11,196 @@ namespace Symfony\Bundle\FrameworkBundle; +use Symfony\Component\BrowserKit\CookieJar; +use Symfony\Component\BrowserKit\History; +use Symfony\Component\DependencyInjection\ContainerInterface; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpKernel\HttpKernelBrowser; +use Symfony\Component\HttpKernel\KernelInterface; +use Symfony\Component\HttpKernel\Profiler\Profile as HttpProfile; + /** - * Client simulates a browser and makes requests to a Kernel object. + * Simulates a browser and makes requests to a Kernel object. * * @author Fabien Potencier */ -class KernelBrowser extends Client +class KernelBrowser extends HttpKernelBrowser { + private $hasPerformedRequest = false; + private $profiler = false; + private $reboot = true; + + /** + * {@inheritdoc} + */ + public function __construct(KernelInterface $kernel, array $server = [], History $history = null, CookieJar $cookieJar = null) + { + parent::__construct($kernel, $server, $history, $cookieJar); + } + + /** + * Returns the container. + * + * @return ContainerInterface|null Returns null when the Kernel has been shutdown or not started yet + */ + public function getContainer() + { + return $this->kernel->getContainer(); + } + + /** + * Returns the kernel. + * + * @return KernelInterface + */ + public function getKernel() + { + return $this->kernel; + } + + /** + * Gets the profile associated with the current Response. + * + * @return HttpProfile|false A Profile instance + */ + public function getProfile() + { + if (null === $this->response || !$this->kernel->getContainer()->has('profiler')) { + return false; + } + + return $this->kernel->getContainer()->get('profiler')->loadProfileFromResponse($this->response); + } + + /** + * Enables the profiler for the very next request. + * + * If the profiler is not enabled, the call to this method does nothing. + */ + public function enableProfiler() + { + if ($this->kernel->getContainer()->has('profiler')) { + $this->profiler = true; + } + } + + /** + * Disables kernel reboot between requests. + * + * By default, the Client reboots the Kernel for each request. This method + * allows to keep the same kernel across requests. + */ + public function disableReboot() + { + $this->reboot = false; + } + + /** + * Enables kernel reboot between requests. + */ + public function enableReboot() + { + $this->reboot = true; + } + + /** + * {@inheritdoc} + * + * @param Request $request A Request instance + * + * @return Response A Response instance + */ + protected function doRequest($request) + { + // avoid shutting down the Kernel if no request has been performed yet + // WebTestCase::createClient() boots the Kernel but do not handle a request + if ($this->hasPerformedRequest && $this->reboot) { + $this->kernel->shutdown(); + } else { + $this->hasPerformedRequest = true; + } + + if ($this->profiler) { + $this->profiler = false; + + $this->kernel->boot(); + $this->kernel->getContainer()->get('profiler')->enable(); + } + + return parent::doRequest($request); + } + + /** + * {@inheritdoc} + * + * @param Request $request A Request instance + * + * @return Response A Response instance + */ + protected function doRequestInProcess($request) + { + $response = parent::doRequestInProcess($request); + + $this->profiler = false; + + return $response; + } + + /** + * Returns the script to execute when the request must be insulated. + * + * It assumes that the autoloader is named 'autoload.php' and that it is + * stored in the same directory as the kernel (this is the case for the + * Symfony Standard Edition). If this is not your case, create your own + * client and override this method. + * + * @param Request $request A Request instance + * + * @return string The script content + */ + protected function getScript($request) + { + $kernel = var_export(serialize($this->kernel), true); + $request = var_export(serialize($request), true); + $errorReporting = error_reporting(); + + $requires = ''; + foreach (get_declared_classes() as $class) { + if (0 === strpos($class, 'ComposerAutoloaderInit')) { + $r = new \ReflectionClass($class); + $file = \dirname($r->getFileName(), 2).'/autoload.php'; + if (file_exists($file)) { + $requires .= 'require_once '.var_export($file, true).";\n"; + } + } + } + + if (!$requires) { + throw new \RuntimeException('Composer autoloader not found.'); + } + + $requires .= 'require_once '.var_export((new \ReflectionObject($this->kernel))->getFileName(), true).";\n"; + + $profilerCode = ''; + if ($this->profiler) { + $profilerCode = '$kernel->getContainer()->get(\'profiler\')->enable();'; + } + + $code = <<boot(); +$profilerCode + +\$request = unserialize($request); +EOF; + + return $code.$this->getHandleScript(); + } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/cache.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/cache.xml index 41264e9d1acab..9959debfa94a5 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/cache.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/cache.xml @@ -11,11 +11,6 @@ - - The "Psr\SimpleCache\CacheInterface" / "%service_id%" service is deprecated since Symfony 4.3. Use "Symfony\Contracts\Cache\CacheInterface" / "cache.app" instead. - - - @@ -155,7 +150,6 @@ - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/console.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/console.xml index 7276892940acb..6333f2d3cd0df 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/console.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/console.xml @@ -93,7 +93,6 @@ - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/fragment_renderer.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/fragment_renderer.xml index 394033734d2d4..827a22f9a4668 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/fragment_renderer.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/fragment_renderer.xml @@ -26,7 +26,7 @@ - + %fragment.renderer.hinclude.global_template% %fragment.path% diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/identity_translator.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/identity_translator.xml index 4d2d488edb354..9dccb43ee52e0 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/identity_translator.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/identity_translator.xml @@ -7,12 +7,8 @@ - - - The "%service_id%" service is deprecated since Symfony 4.2, use "identity_translator" instead. - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/lock.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/lock.xml index a82003c004a15..86b8571c083e9 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/lock.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/lock.xml @@ -7,24 +7,6 @@ - - The "%service_id%" service is deprecated since Symfony 4.4 and will be removed in 5.0. - - - - The "%service_id%" service is deprecated since Symfony 4.4 and will be removed in 5.0. - - - - - The "%service_id%" service is deprecated since Symfony 4.4 and will be removed in 5.0. - - - - - The "%service_id%" service is deprecated since Symfony 4.4 and will be removed in 5.0. - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/notifier.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/notifier.xml new file mode 100644 index 0000000000000..dfc6cdccd34c7 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/notifier.xml @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/notifier_transports.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/notifier_transports.xml new file mode 100644 index 0000000000000..c4d9cf892adca --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/notifier_transports.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/routing.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/routing.xml index b85e9fa71d1cc..49a39360dae38 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/routing.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/routing.xml @@ -40,25 +40,14 @@ - - - The "%service_id%" service is deprecated since Symfony 4.4, use "routing.loader.container" instead. - - - - - - - - + - @@ -124,7 +113,6 @@ - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd b/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd index ae1c75dcc96eb..b8e4488456f2c 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/schema/symfony-1.0.xsd @@ -20,7 +20,6 @@ - @@ -160,18 +159,6 @@ - - - - - - - - - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/services.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/services.xml index 5d8508f97dbe9..ac406aad077bc 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/services.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/services.xml @@ -83,11 +83,6 @@ - %kernel.root_dir%/Resources - - %kernel.root_dir% - - false @@ -127,5 +122,11 @@ + + + %kernel.default_locale% + + + diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/session.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/session.xml index 5aae3b4d9feca..0cb7b4e200fe9 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/session.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/session.xml @@ -69,10 +69,6 @@ - - The "%service_id%" service is deprecated since Symfony 4.1. Use the "session_listener" service instead. - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/templating.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/templating.xml deleted file mode 100644 index b6b70be999de8..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/templating.xml +++ /dev/null @@ -1,67 +0,0 @@ - - - - - - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - %kernel.cache_dir% - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - %kernel.root_dir%/Resources - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - %templating.loader.cache.path% - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/templating_debug.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/templating_debug.xml deleted file mode 100644 index 3dd7b84c123ba..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/templating_debug.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - %kernel.charset% - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/templating_php.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/templating_php.xml deleted file mode 100644 index 440b9a5d23298..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/templating_php.xml +++ /dev/null @@ -1,116 +0,0 @@ - - - - - - - - - - - - - %kernel.charset% - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - %kernel.project_dir% - %kernel.charset% - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - %templating.helper.form.resources% - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/translation.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/translation.xml index a9d5a85d202e8..07213a2602df4 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/translation.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/translation.xml @@ -21,7 +21,6 @@ - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/validator.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/validator.xml index f2d0e9e2a603b..070908f3db351 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/validator.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/validator.xml @@ -38,11 +38,6 @@ - - - The "%service_id%" service is deprecated since Symfony 4.4. Use validator.mapping.cache.adapter instead. - - %validator.mapping.cache.file% diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml index aff90a584b87d..cbdc5586a27ad 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/web.xml @@ -7,21 +7,10 @@ - - - - false - - - - The "%alias_id%" service is deprecated since Symfony 4.3. - - - @@ -76,15 +65,6 @@ - - - false - - - - The "%alias_id%" service is deprecated since Symfony 4.3. - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/config/workflow.xml b/src/Symfony/Bundle/FrameworkBundle/Resources/config/workflow.xml index 0bba153b10317..78741deb8ebbf 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/config/workflow.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Resources/config/workflow.xml @@ -20,8 +20,6 @@ - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/attributes.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/attributes.html.php deleted file mode 100644 index 047d342a8d5c3..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/attributes.html.php +++ /dev/null @@ -1,9 +0,0 @@ - $v): ?> - -escape($k), $view->escape(false !== $translation_domain ? $view['translator']->trans($v, $attr_translation_parameters, $translation_domain) : $v)) ?> - -escape($k), $view->escape($k)) ?> - -escape($k), $view->escape($v)) ?> - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/button_attributes.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/button_attributes.html.php deleted file mode 100644 index 279233baa3fc0..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/button_attributes.html.php +++ /dev/null @@ -1,2 +0,0 @@ -id="escape($id) ?>" name="escape($full_name) ?>" disabled="disabled" -block($form, 'attributes') : '' ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/button_label.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/button_label.html.php deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/button_row.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/button_row.html.php deleted file mode 100644 index b52e92984533d..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/button_row.html.php +++ /dev/null @@ -1,3 +0,0 @@ -
- widget($form) ?> -
diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/button_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/button_widget.html.php deleted file mode 100644 index 42a7c5db02d8f..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/button_widget.html.php +++ /dev/null @@ -1,4 +0,0 @@ - $name, '%id%' => $id]) - : $view['form']->humanize($name); } ?> - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/checkbox_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/checkbox_widget.html.php deleted file mode 100644 index 143557dea8a64..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/checkbox_widget.html.php +++ /dev/null @@ -1,5 +0,0 @@ -block($form, 'widget_attributes') ?> - 0): ?> value="escape($value) ?>" - checked="checked" -/> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_attributes.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_attributes.html.php deleted file mode 100644 index 18f8368dc8065..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_attributes.html.php +++ /dev/null @@ -1,8 +0,0 @@ -disabled="disabled" - $v): ?> - -escape($k), $view->escape($k)) ?> - -escape($k), $view->escape($v)) ?> - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_options.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_options.html.php deleted file mode 100644 index 211ae73f1c3d1..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_options.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'choice_widget_options') ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget.html.php deleted file mode 100644 index 13593a96f11ef..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget.html.php +++ /dev/null @@ -1,5 +0,0 @@ - -block($form, 'choice_widget_expanded') ?> - -block($form, 'choice_widget_collapsed') ?> - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_collapsed.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_collapsed.html.php deleted file mode 100644 index 6a57d585c7b57..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_collapsed.html.php +++ /dev/null @@ -1,18 +0,0 @@ - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_expanded.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_expanded.html.php deleted file mode 100644 index 9691759a907f5..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_expanded.html.php +++ /dev/null @@ -1,6 +0,0 @@ -
block($form, 'widget_container_attributes') ?>> - - widget($child) ?> - label($child, null, ['translation_domain' => $choice_translation_domain]) ?> - -
diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_options.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_options.html.php deleted file mode 100644 index a19b5a5e6e0b8..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/choice_widget_options.html.php +++ /dev/null @@ -1,13 +0,0 @@ - - - $choice): ?> - - - block($form, 'choice_widget_options', ['choices' => $choice]) ?> - - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/collection_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/collection_widget.html.php deleted file mode 100644 index 40dfdaf1f031f..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/collection_widget.html.php +++ /dev/null @@ -1,4 +0,0 @@ - - escape($view['form']->row($prototype)) ?> - -widget($form, ['attr' => $attr]) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/color_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/color_widget.html.php deleted file mode 100644 index 48f5c2c30dfd5..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/color_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'form_widget_simple', ['type' => isset($type) ? $type : 'color']); diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/container_attributes.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/container_attributes.html.php deleted file mode 100644 index 302bbfcd479d9..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/container_attributes.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'widget_container_attributes') ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/date_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/date_widget.html.php deleted file mode 100644 index fbd844f28693b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/date_widget.html.php +++ /dev/null @@ -1,11 +0,0 @@ - - block($form, 'form_widget_simple'); ?> - -
block($form, 'widget_container_attributes') ?>> - widget($form['year']), - $view['form']->widget($form['month']), - $view['form']->widget($form['day']), - ], $date_pattern) ?> -
- diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/datetime_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/datetime_widget.html.php deleted file mode 100644 index aef2a32512f72..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/datetime_widget.html.php +++ /dev/null @@ -1,7 +0,0 @@ - - block($form, 'form_widget_simple'); ?> - -
block($form, 'widget_container_attributes') ?>> - widget($form['date']).' '.$view['form']->widget($form['time']) ?> -
- diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/email_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/email_widget.html.php deleted file mode 100644 index fa6b0ee8a14a4..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/email_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'form_widget_simple', ['type' => isset($type) ? $type : 'email']) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form.html.php deleted file mode 100644 index fb789faff723a..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form.html.php +++ /dev/null @@ -1,3 +0,0 @@ -start($form) ?> - widget($form) ?> -end($form) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_enctype.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_enctype.html.php deleted file mode 100644 index 36eba3c9e8e7a..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_enctype.html.php +++ /dev/null @@ -1 +0,0 @@ -vars['multipart']): ?>enctype="multipart/form-data" diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_end.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_end.html.php deleted file mode 100644 index fe6843905cee5..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_end.html.php +++ /dev/null @@ -1,4 +0,0 @@ - -rest($form) ?> - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_errors.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_errors.html.php deleted file mode 100644 index d97179e9a680c..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_errors.html.php +++ /dev/null @@ -1,7 +0,0 @@ - 0): ?> -
    - -
  • escape($error->getMessage()) ?>
  • - -
- diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_help.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_help.html.php deleted file mode 100644 index 9e3ed9b6c6e44..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_help.html.php +++ /dev/null @@ -1,6 +0,0 @@ - - - trans($help, $help_translation_parameters, $translation_domain) : $help; ?> - escape($help) : $help ?> -

block($form, 'attributes', ['attr' => $help_attr]); ?>>

- diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_label.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_label.html.php deleted file mode 100644 index b3465042efddd..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_label.html.php +++ /dev/null @@ -1,8 +0,0 @@ - - - - $name, '%id%' => $id]) - : $view['form']->humanize($name); } ?> -block($form, 'attributes', ['attr' => $label_attr]); } ?>>escape(false !== $translation_domain ? $view['translator']->trans($label, $label_translation_parameters, $translation_domain) : $label) ?> - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_rest.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_rest.html.php deleted file mode 100644 index 89041c6ec6374..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_rest.html.php +++ /dev/null @@ -1,5 +0,0 @@ - - isRendered()): ?> - row($child) ?> - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_row.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_row.html.php deleted file mode 100644 index b6e750aa79f4b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_row.html.php +++ /dev/null @@ -1,7 +0,0 @@ -
- ['aria-describedby' => $id.'_help']]; ?> - label($form); ?> - errors($form); ?> - widget($form, $widgetAttr); ?> - help($form); ?> -
diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_rows.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_rows.html.php deleted file mode 100644 index 4de226f2b8b2a..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_rows.html.php +++ /dev/null @@ -1,5 +0,0 @@ - - isRendered()): ?> - row($child) ?> - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_start.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_start.html.php deleted file mode 100644 index 7e244258053ff..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_start.html.php +++ /dev/null @@ -1,6 +0,0 @@ - - -
action="escape($action) ?>" $v) { printf(' %s="%s"', $view->escape($k), $view->escape($v)); } ?> enctype="multipart/form-data"> - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_widget.html.php deleted file mode 100644 index c5af39a5b6b06..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_widget.html.php +++ /dev/null @@ -1,5 +0,0 @@ - -block($form, 'form_widget_compound')?> - -block($form, 'form_widget_simple')?> - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_widget_compound.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_widget_compound.html.php deleted file mode 100644 index 7a4f7cd51fb3a..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_widget_compound.html.php +++ /dev/null @@ -1,7 +0,0 @@ -
block($form, 'widget_container_attributes') ?>> - parent && $errors): ?> - errors($form) ?> - - block($form, 'form_rows') ?> - rest($form) ?> -
diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_widget_simple.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_widget_simple.html.php deleted file mode 100644 index 5d7654f54cdc6..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/form_widget_simple.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'widget_attributes') ?> value="escape($value) ?>" /> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/hidden_row.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/hidden_row.html.php deleted file mode 100644 index 3239d8f415b12..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/hidden_row.html.php +++ /dev/null @@ -1 +0,0 @@ -widget($form) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/hidden_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/hidden_widget.html.php deleted file mode 100644 index 6bcbb5e0461a9..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/hidden_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'form_widget_simple', ['type' => isset($type) ? $type : 'hidden']) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/integer_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/integer_widget.html.php deleted file mode 100644 index faaff51e676f5..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/integer_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'form_widget_simple', ['type' => isset($type) ? $type : 'number']) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/money_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/money_widget.html.php deleted file mode 100644 index 25fe13f7e057c..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/money_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -formEncodeCurrency($money_pattern, $view['form']->block($form, 'form_widget_simple')) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/number_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/number_widget.html.php deleted file mode 100644 index 3d6f79c63bedb..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/number_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'form_widget_simple', ['type' => isset($type) ? $type : 'text']) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/password_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/password_widget.html.php deleted file mode 100644 index 5514468f6a1b3..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/password_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'form_widget_simple', ['type' => isset($type) ? $type : 'password']) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/percent_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/percent_widget.html.php deleted file mode 100644 index 163e1f18f611c..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/percent_widget.html.php +++ /dev/null @@ -1,2 +0,0 @@ - -block($form, 'form_widget_simple', ['type' => isset($type) ? $type : 'text']).$view->escape($symbol) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/radio_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/radio_widget.html.php deleted file mode 100644 index ddc8c529dff67..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/radio_widget.html.php +++ /dev/null @@ -1,5 +0,0 @@ -block($form, 'widget_attributes') ?> - value="escape($value) ?>" - checked="checked" -/> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/range_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/range_widget.html.php deleted file mode 100644 index d6650d8154676..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/range_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'form_widget_simple', ['type' => isset($type) ? $type : 'range']); diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/repeated_row.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/repeated_row.html.php deleted file mode 100644 index d4af23d712320..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/repeated_row.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'form_rows') ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/reset_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/reset_widget.html.php deleted file mode 100644 index af45b1566998a..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/reset_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'button_widget', ['type' => isset($type) ? $type : 'reset']) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/search_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/search_widget.html.php deleted file mode 100644 index 191279b517eb2..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/search_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'form_widget_simple', ['type' => isset($type) ? $type : 'search']) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/submit_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/submit_widget.html.php deleted file mode 100644 index baea833326334..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/submit_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'button_widget', ['type' => isset($type) ? $type : 'submit']) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/tel_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/tel_widget.html.php deleted file mode 100644 index dd471b9518d20..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/tel_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'form_widget_simple', ['type' => isset($type) ? $type : 'tel']); diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/textarea_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/textarea_widget.html.php deleted file mode 100644 index c989ce575d579..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/textarea_widget.html.php +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/time_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/time_widget.html.php deleted file mode 100644 index cd2f5596011c1..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/time_widget.html.php +++ /dev/null @@ -1,22 +0,0 @@ - - block($form, 'form_widget_simple'); ?> - - ['size' => 1]] : [] ?> -
block($form, 'widget_container_attributes') ?>> - widget($form['hour'], $vars); - - if ($with_minutes) { - echo ':'; - echo $view['form']->widget($form['minute'], $vars); - } - - if ($with_seconds) { - echo ':'; - echo $view['form']->widget($form['second'], $vars); - } - ?> -
- diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/url_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/url_widget.html.php deleted file mode 100644 index cd653c89c5ccc..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/url_widget.html.php +++ /dev/null @@ -1 +0,0 @@ -block($form, 'form_widget_simple', ['type' => isset($type) ? $type : 'url']) ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/widget_attributes.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/widget_attributes.html.php deleted file mode 100644 index 1626a9cc63ff5..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/widget_attributes.html.php +++ /dev/null @@ -1,3 +0,0 @@ -id="escape($id) ?>" name="escape($full_name) ?>" disabled="disabled" - required="required" -block($form, 'attributes') : '' ?> \ No newline at end of file diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/widget_container_attributes.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/widget_container_attributes.html.php deleted file mode 100644 index fdd176d12c79f..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/Form/widget_container_attributes.html.php +++ /dev/null @@ -1,2 +0,0 @@ -id="escape($id) ?>" -block($form, 'attributes') : '' ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/FormTable/button_row.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/FormTable/button_row.html.php deleted file mode 100644 index 67d0137e20b97..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/FormTable/button_row.html.php +++ /dev/null @@ -1,6 +0,0 @@ - - - - widget($form); ?> - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/FormTable/form_row.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/FormTable/form_row.html.php deleted file mode 100644 index 92b87e1b679bd..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/FormTable/form_row.html.php +++ /dev/null @@ -1,11 +0,0 @@ - - ['aria-describedby' => $id.'_help']]; ?> - - label($form); ?> - - - errors($form); ?> - widget($form, $widgetAttr); ?> - help($form); ?> - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/FormTable/form_widget_compound.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/FormTable/form_widget_compound.html.php deleted file mode 100644 index adc897338861b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/FormTable/form_widget_compound.html.php +++ /dev/null @@ -1,11 +0,0 @@ -block($form, 'widget_container_attributes'); ?>> - parent && $errors): ?> - - - - - block($form, 'form_rows'); ?> - rest($form); ?> -
- errors($form); ?> -
diff --git a/src/Symfony/Bundle/FrameworkBundle/Resources/views/FormTable/hidden_row.html.php b/src/Symfony/Bundle/FrameworkBundle/Resources/views/FormTable/hidden_row.html.php deleted file mode 100644 index 116b300bd5619..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Resources/views/FormTable/hidden_row.html.php +++ /dev/null @@ -1,5 +0,0 @@ - - - widget($form); ?> - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php b/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php index 5f24d587a44e8..f25bdf32d77b1 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php +++ b/src/Symfony/Bundle/FrameworkBundle/Routing/DelegatingLoader.php @@ -11,7 +11,6 @@ namespace Symfony\Bundle\FrameworkBundle\Routing; -use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser; use Symfony\Component\Config\Exception\LoaderLoadException; use Symfony\Component\Config\Loader\DelegatingLoader as BaseDelegatingLoader; use Symfony\Component\Config\Loader\LoaderResolverInterface; @@ -24,32 +23,15 @@ * * @author Fabien Potencier * - * @final since Symfony 4.4 + * @final */ class DelegatingLoader extends BaseDelegatingLoader { - /** - * @deprecated since Symfony 4.4 - */ - protected $parser; private $loading = false; private $defaultOptions; - /** - * @param LoaderResolverInterface $resolver - * @param array $defaultOptions - */ - public function __construct($resolver, $defaultOptions = []) + public function __construct(LoaderResolverInterface $resolver, array $defaultOptions = []) { - if ($resolver instanceof ControllerNameParser) { - @trigger_error(sprintf('Passing a "%s" instance as first argument to "%s()" is deprecated since Symfony 4.4, pass a "%s" instance instead.', ControllerNameParser::class, __METHOD__, LoaderResolverInterface::class), E_USER_DEPRECATED); - $this->parser = $resolver; - $resolver = $defaultOptions; - $defaultOptions = 2 < \func_num_args() ? func_get_arg(2) : []; - } elseif (2 < \func_num_args() && func_get_arg(2) instanceof ControllerNameParser) { - $this->parser = func_get_arg(2); - } - $this->defaultOptions = $defaultOptions; parent::__construct($resolver); @@ -58,7 +40,7 @@ public function __construct($resolver, $defaultOptions = []) /** * {@inheritdoc} */ - public function load($resource, $type = null) + public function load($resource, string $type = null) { if ($this->loading) { // This can happen if a fatal error occurs in parent::load(). @@ -99,18 +81,6 @@ public function load($resource, $type = null) continue; } - if ($this->parser && 2 === substr_count($controller, ':')) { - $deprecatedNotation = $controller; - - try { - $controller = $this->parser->parse($controller, false); - - @trigger_error(sprintf('Referencing controllers with %s is deprecated since Symfony 4.1, use "%s" instead.', $deprecatedNotation, $controller), E_USER_DEPRECATED); - } catch (\InvalidArgumentException $e) { - // unable to optimize unknown notation - } - } - $route->setDefault('_controller', $controller); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Routing/LegacyRouteLoaderContainer.php b/src/Symfony/Bundle/FrameworkBundle/Routing/LegacyRouteLoaderContainer.php deleted file mode 100644 index 741fe210f2001..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Routing/LegacyRouteLoaderContainer.php +++ /dev/null @@ -1,53 +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\Routing; - -use Psr\Container\ContainerInterface; - -/** - * @internal to be removed in Symfony 5.0 - */ -class LegacyRouteLoaderContainer implements ContainerInterface -{ - private $container; - private $serviceLocator; - - public function __construct(ContainerInterface $container, ContainerInterface $serviceLocator) - { - $this->container = $container; - $this->serviceLocator = $serviceLocator; - } - - /** - * {@inheritdoc} - */ - public function get($id) - { - if ($this->serviceLocator->has($id)) { - return $this->serviceLocator->get($id); - } - - @trigger_error(sprintf('Registering the service route loader "%s" without tagging it with the "routing.route_loader" tag is deprecated since Symfony 4.4 and will be required in Symfony 5.0.', $id), E_USER_DEPRECATED); - - return $this->container->get($id); - } - - /** - * {@inheritdoc} - * - * @return bool - */ - public function has($id) - { - return $this->serviceLocator->has($id) || $this->container->has($id); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableCompiledUrlMatcher.php b/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableCompiledUrlMatcher.php index cb2c831d969fd..dba9d6d9613d1 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableCompiledUrlMatcher.php +++ b/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableCompiledUrlMatcher.php @@ -24,7 +24,7 @@ class RedirectableCompiledUrlMatcher extends CompiledUrlMatcher implements Redir /** * {@inheritdoc} */ - public function redirect($path, $route, $scheme = null): array + public function redirect(string $path, string $route, string $scheme = null): array { return [ '_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::urlRedirectAction', diff --git a/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php b/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php deleted file mode 100644 index 13ad12dccf866..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Routing/RedirectableUrlMatcher.php +++ /dev/null @@ -1,46 +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\Routing; - -@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.3.', RedirectableUrlMatcher::class), E_USER_DEPRECATED); - -use Symfony\Component\Routing\Matcher\RedirectableUrlMatcher as BaseMatcher; - -/** - * @author Fabien Potencier - * - * @deprecated since Symfony 4.3 - */ -class RedirectableUrlMatcher extends BaseMatcher -{ - /** - * Redirects the user to another URL. - * - * @param string $path The path info to redirect to - * @param string $route The route that matched - * @param string $scheme The URL scheme (null to keep the current one) - * - * @return array An array of parameters - */ - public function redirect($path, $route, $scheme = null) - { - return [ - '_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::urlRedirectAction', - 'path' => $path, - 'permanent' => true, - 'scheme' => $scheme, - 'httpPort' => $this->context->getHttpPort(), - 'httpsPort' => $this->context->getHttpsPort(), - '_route' => $route, - ]; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Routing/Router.php b/src/Symfony/Bundle/FrameworkBundle/Routing/Router.php index 83f6602b98a85..f9def3da5be95 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Routing/Router.php +++ b/src/Symfony/Bundle/FrameworkBundle/Routing/Router.php @@ -13,7 +13,6 @@ use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; -use Symfony\Bundle\FrameworkBundle\DependencyInjection\CompatibilityServiceSubscriberInterface as ServiceSubscriberInterface; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\DependencyInjection\Config\ContainerParametersResource; use Symfony\Component\DependencyInjection\ContainerInterface as SymfonyContainerInterface; @@ -23,6 +22,7 @@ use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\Router as BaseRouter; +use Symfony\Contracts\Service\ServiceSubscriberInterface; /** * This Router creates the Loader only when the cache is empty. @@ -74,7 +74,7 @@ public function getRouteCollection() /** * {@inheritdoc} */ - public function warmUp($cacheDir) + public function warmUp(string $cacheDir) { $currentDir = $this->getOption('cache_dir'); diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/DelegatingEngine.php b/src/Symfony/Bundle/FrameworkBundle/Templating/DelegatingEngine.php deleted file mode 100644 index bd292e468160b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/DelegatingEngine.php +++ /dev/null @@ -1,78 +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\Templating; - -@trigger_error('The '.DelegatingEngine::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Psr\Container\ContainerInterface; -use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\Templating\DelegatingEngine as BaseDelegatingEngine; - -/** - * DelegatingEngine selects an engine for a given template. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class DelegatingEngine extends BaseDelegatingEngine implements EngineInterface -{ - protected $container; - - public function __construct(ContainerInterface $container, array $engineIds) - { - $this->container = $container; - $this->engines = $engineIds; - } - - /** - * {@inheritdoc} - */ - public function getEngine($name) - { - $this->resolveEngines(); - - return parent::getEngine($name); - } - - /** - * {@inheritdoc} - */ - public function renderResponse($view, array $parameters = [], Response $response = null) - { - $engine = $this->getEngine($view); - - if ($engine instanceof EngineInterface) { - return $engine->renderResponse($view, $parameters, $response); - } - - if (null === $response) { - $response = new Response(); - } - - $response->setContent($engine->render($view, $parameters)); - - return $response; - } - - /** - * Resolved engine ids to their real engine instances from the container. - */ - private function resolveEngines() - { - foreach ($this->engines as $i => $engine) { - if (\is_string($engine)) { - $this->engines[$i] = $this->container->get($engine); - } - } - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/EngineInterface.php b/src/Symfony/Bundle/FrameworkBundle/Templating/EngineInterface.php deleted file mode 100644 index 39aa15eb4c980..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/EngineInterface.php +++ /dev/null @@ -1,39 +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\Templating; - -@trigger_error('The '.EngineInterface::class.' interface is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\Templating\EngineInterface as BaseEngineInterface; - -/** - * EngineInterface is the interface each engine must implement. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -interface EngineInterface extends BaseEngineInterface -{ - /** - * Renders a view and returns a Response. - * - * @param string $view The view name - * @param array $parameters An array of parameters to pass to the view - * - * @return Response A Response instance - * - * @throws \RuntimeException if the template cannot be rendered - */ - public function renderResponse($view, array $parameters = [], Response $response = null); -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/GlobalVariables.php b/src/Symfony/Bundle/FrameworkBundle/Templating/GlobalVariables.php deleted file mode 100644 index 22b2551ac6b2f..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/GlobalVariables.php +++ /dev/null @@ -1,93 +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\Templating; - -@trigger_error('The '.GlobalVariables::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\DependencyInjection\ContainerInterface; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Session\Session; -use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; - -/** - * GlobalVariables is the entry point for Symfony global variables in PHP templates. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class GlobalVariables -{ - protected $container; - - public function __construct(ContainerInterface $container) - { - $this->container = $container; - } - - /** - * @return TokenInterface|null - */ - public function getToken() - { - if (!$this->container->has('security.token_storage')) { - return null; - } - - return $this->container->get('security.token_storage')->getToken(); - } - - public function getUser() - { - if (!$token = $this->getToken()) { - return null; - } - - $user = $token->getUser(); - - return \is_object($user) ? $user : null; - } - - /** - * @return Request|null The HTTP request object - */ - public function getRequest() - { - return $this->container->has('request_stack') ? $this->container->get('request_stack')->getCurrentRequest() : null; - } - - /** - * @return Session|null The session - */ - public function getSession() - { - $request = $this->getRequest(); - - return $request && $request->hasSession() ? $request->getSession() : null; - } - - /** - * @return string The current environment string (e.g 'dev') - */ - public function getEnvironment() - { - return $this->container->getParameter('kernel.environment'); - } - - /** - * @return bool The current debug mode - */ - public function getDebug() - { - return (bool) $this->container->getParameter('kernel.debug'); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/ActionsHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/ActionsHelper.php deleted file mode 100644 index a6eb19fd0f108..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/ActionsHelper.php +++ /dev/null @@ -1,65 +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\Templating\Helper; - -@trigger_error('The '.ActionsHelper::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\HttpKernel\Controller\ControllerReference; -use Symfony\Component\HttpKernel\Fragment\FragmentHandler; -use Symfony\Component\Templating\Helper\Helper; - -/** - * ActionsHelper manages action inclusions. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class ActionsHelper extends Helper -{ - private $handler; - - public function __construct(FragmentHandler $handler) - { - $this->handler = $handler; - } - - /** - * Returns the fragment content for a given URI. - * - * @param string $uri - * - * @return string The fragment content - * - * @see FragmentHandler::render() - */ - public function render($uri, array $options = []) - { - $strategy = isset($options['strategy']) ? $options['strategy'] : 'inline'; - unset($options['strategy']); - - return $this->handler->render($uri, $strategy, $options); - } - - public function controller($controller, $attributes = [], $query = []) - { - return new ControllerReference($controller, $attributes, $query); - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'actions'; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/AssetsHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/AssetsHelper.php deleted file mode 100644 index ff237d6a9728a..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/AssetsHelper.php +++ /dev/null @@ -1,71 +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\Templating\Helper; - -@trigger_error('The '.AssetsHelper::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\Asset\Packages; -use Symfony\Component\Templating\Helper\Helper; - -/** - * AssetsHelper helps manage asset URLs. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class AssetsHelper extends Helper -{ - private $packages; - - public function __construct(Packages $packages) - { - $this->packages = $packages; - } - - /** - * Returns the public url/path of an asset. - * - * If the package used to generate the path is an instance of - * UrlPackage, you will always get a URL and not a path. - * - * @param string $path A public path - * @param string $packageName The name of the asset package to use - * - * @return string The public path of the asset - */ - public function getUrl($path, $packageName = null) - { - return $this->packages->getUrl($path, $packageName); - } - - /** - * Returns the version of an asset. - * - * @param string $path A public path - * @param string $packageName The name of the asset package to use - * - * @return string The asset version - */ - public function getVersion($path, $packageName = null) - { - return $this->packages->getVersion($path, $packageName); - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'assets'; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/CodeHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/CodeHelper.php deleted file mode 100644 index 4e5973428d19d..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/CodeHelper.php +++ /dev/null @@ -1,233 +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\Templating\Helper; - -@trigger_error('The '.CodeHelper::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\HttpKernel\Debug\FileLinkFormatter; -use Symfony\Component\Templating\Helper\Helper; - -/** - * @author Fabien Potencier - * - * @internal since Symfony 4.2 - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class CodeHelper extends Helper -{ - protected $fileLinkFormat; - protected $rootDir; // to be renamed $projectDir in 5.0 - protected $charset; - - /** - * @param string|FileLinkFormatter $fileLinkFormat The format for links to source files - * @param string $projectDir The project root directory - * @param string $charset The charset - */ - public function __construct($fileLinkFormat, string $projectDir, string $charset) - { - $this->fileLinkFormat = $fileLinkFormat ?: ini_get('xdebug.file_link_format') ?: get_cfg_var('xdebug.file_link_format'); - $this->rootDir = str_replace('\\', '/', $projectDir).'/'; - $this->charset = $charset; - } - - /** - * Formats an array as a string. - * - * @param array $args The argument array - * - * @return string - */ - public function formatArgsAsText(array $args) - { - return strip_tags($this->formatArgs($args)); - } - - public function abbrClass($class) - { - $parts = explode('\\', $class); - $short = array_pop($parts); - - return sprintf('%s', $class, $short); - } - - public function abbrMethod($method) - { - if (false !== strpos($method, '::')) { - list($class, $method) = explode('::', $method, 2); - $result = sprintf('%s::%s()', $this->abbrClass($class), $method); - } elseif ('Closure' === $method) { - $result = sprintf('%1$s', $method); - } else { - $result = sprintf('%1$s()', $method); - } - - return $result; - } - - /** - * Formats an array as a string. - * - * @param array $args The argument array - * - * @return string - */ - public function formatArgs(array $args) - { - $result = []; - foreach ($args as $key => $item) { - if ('object' === $item[0]) { - $parts = explode('\\', $item[1]); - $short = array_pop($parts); - $formattedValue = sprintf('object(%s)', $item[1], $short); - } elseif ('array' === $item[0]) { - $formattedValue = sprintf('array(%s)', \is_array($item[1]) ? $this->formatArgs($item[1]) : $item[1]); - } elseif ('string' === $item[0]) { - $formattedValue = sprintf("'%s'", htmlspecialchars($item[1], ENT_QUOTES, $this->getCharset())); - } elseif ('null' === $item[0]) { - $formattedValue = 'null'; - } elseif ('boolean' === $item[0]) { - $formattedValue = ''.strtolower(var_export($item[1], true)).''; - } elseif ('resource' === $item[0]) { - $formattedValue = 'resource'; - } else { - $formattedValue = str_replace("\n", '', var_export(htmlspecialchars((string) $item[1], ENT_QUOTES, $this->getCharset()), true)); - } - - $result[] = \is_int($key) ? $formattedValue : sprintf("'%s' => %s", $key, $formattedValue); - } - - return implode(', ', $result); - } - - /** - * Returns an excerpt of a code file around the given line number. - * - * @param string $file A file path - * @param int $line The selected line number - * - * @return string|null An HTML string - */ - public function fileExcerpt($file, $line) - { - if (is_readable($file)) { - if (\extension_loaded('fileinfo')) { - $finfo = new \finfo(); - - // 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 ''; - } - } - - // highlight_file could throw warnings - // see https://bugs.php.net/25725 - $code = @highlight_file($file, true); - // remove main code/span tags - $code = preg_replace('#^\s*(.*)\s*#s', '\\1', $code); - $content = explode('
', $code); - - $lines = []; - for ($i = max($line - 3, 1), $max = min($line + 3, \count($content)); $i <= $max; ++$i) { - $lines[] = ''.self::fixCodeMarkup($content[$i - 1]).''; - } - - return '
    '.implode("\n", $lines).'
'; - } - - return null; - } - - /** - * Formats a file path. - * - * @param string $file An absolute file path - * @param int $line The line number - * @param string $text Use this text for the link rather than the file path - * - * @return string - */ - public function formatFile($file, $line, $text = null) - { - $flags = ENT_QUOTES | ENT_SUBSTITUTE; - - if (null === $text) { - $file = trim($file); - $fileStr = $file; - if (0 === strpos($fileStr, $this->rootDir)) { - $fileStr = str_replace(['\\', $this->rootDir], ['/', ''], $fileStr); - $fileStr = htmlspecialchars($fileStr, $flags, $this->charset); - $fileStr = sprintf('kernel.project_dir/%s', htmlspecialchars($this->rootDir, $flags, $this->charset), $fileStr); - } - - $text = sprintf('%s at line %d', $fileStr, $line); - } - - if (false !== $link = $this->getFileLink($file, $line)) { - return sprintf('%s', htmlspecialchars($link, $flags, $this->charset), $text); - } - - return $text; - } - - /** - * Returns the link for a given file/line pair. - * - * @param string $file An absolute file path - * @param int $line The line number - * - * @return string A link of false - */ - public function getFileLink($file, $line) - { - if ($fmt = $this->fileLinkFormat) { - return \is_string($fmt) ? strtr($fmt, ['%f' => $file, '%l' => $line]) : $fmt->format($file, $line); - } - - return false; - } - - public function formatFileFromText($text) - { - return preg_replace_callback('/in ("|")?(.+?)\1(?: +(?:on|at))? +line (\d+)/s', function ($match) { - return 'in '.$this->formatFile($match[2], $match[3]); - }, $text); - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'code'; - } - - protected static function fixCodeMarkup($line) - { - // ending tag from previous line - $opening = strpos($line, ''); - if (false !== $closing && (false === $opening || $closing < $opening)) { - $line = substr_replace($line, '', $closing, 7); - } - - // missing tag at the end of line - $opening = strpos($line, ''); - if (false !== $opening && (false === $closing || $closing > $opening)) { - $line .= ''; - } - - return $line; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/FormHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/FormHelper.php deleted file mode 100644 index fbcf5fcd60007..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/FormHelper.php +++ /dev/null @@ -1,260 +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\Templating\Helper; - -@trigger_error('The '.FormHelper::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\Form\FormRendererInterface; -use Symfony\Component\Form\FormView; -use Symfony\Component\Templating\Helper\Helper; - -/** - * FormHelper provides helpers to help display forms. - * - * @author Fabien Potencier - * @author Bernhard Schussek - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class FormHelper extends Helper -{ - private $renderer; - - public function __construct(FormRendererInterface $renderer) - { - $this->renderer = $renderer; - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'form'; - } - - /** - * Sets a theme for a given view. - * - * The theme format is ":". - * - * @param string|array $themes A theme or an array of theme - * @param bool $useDefaultThemes If true, will use default themes defined in the renderer - */ - public function setTheme(FormView $view, $themes, $useDefaultThemes = true) - { - $this->renderer->setTheme($view, $themes, $useDefaultThemes); - } - - /** - * Renders the HTML for a form. - * - * Example usage: - * - * form($form) ?> - * - * You can pass options during the call: - * - * form($form, ['attr' => ['class' => 'foo']]) ?> - * - * form($form, ['separator' => '+++++']) ?> - * - * This method is mainly intended for prototyping purposes. If you want to - * control the layout of a form in a more fine-grained manner, you are - * advised to use the other helper methods for rendering the parts of the - * form individually. You can also create a custom form theme to adapt - * the look of the form. - * - * @param array $variables Additional variables passed to the template - * - * @return string The HTML markup - */ - public function form(FormView $view, array $variables = []) - { - return $this->renderer->renderBlock($view, 'form', $variables); - } - - /** - * Renders the form start tag. - * - * Example usage templates: - * - * start($form) ?>> - * - * @param array $variables Additional variables passed to the template - * - * @return string The HTML markup - */ - public function start(FormView $view, array $variables = []) - { - return $this->renderer->renderBlock($view, 'form_start', $variables); - } - - /** - * Renders the form end tag. - * - * Example usage templates: - * - * end($form) ?>> - * - * @param array $variables Additional variables passed to the template - * - * @return string The HTML markup - */ - public function end(FormView $view, array $variables = []) - { - return $this->renderer->renderBlock($view, 'form_end', $variables); - } - - /** - * Renders the HTML for a given view. - * - * Example usage: - * - * widget($form) ?> - * - * You can pass options during the call: - * - * widget($form, ['attr' => ['class' => 'foo']]) ?> - * - * widget($form, ['separator' => '+++++']) ?> - * - * @param array $variables Additional variables passed to the template - * - * @return string The HTML markup - */ - public function widget(FormView $view, array $variables = []) - { - return $this->renderer->searchAndRenderBlock($view, 'widget', $variables); - } - - /** - * Renders the entire form field "row". - * - * @param array $variables Additional variables passed to the template - * - * @return string The HTML markup - */ - public function row(FormView $view, array $variables = []) - { - return $this->renderer->searchAndRenderBlock($view, 'row', $variables); - } - - /** - * Renders the label of the given view. - * - * @param string $label The label - * @param array $variables Additional variables passed to the template - * - * @return string The HTML markup - */ - public function label(FormView $view, $label = null, array $variables = []) - { - if (null !== $label) { - $variables += ['label' => $label]; - } - - return $this->renderer->searchAndRenderBlock($view, 'label', $variables); - } - - /** - * Renders the help of the given view. - * - * @return string The HTML markup - */ - public function help(FormView $view): string - { - return $this->renderer->searchAndRenderBlock($view, 'help'); - } - - /** - * Renders the errors of the given view. - * - * @return string The HTML markup - */ - public function errors(FormView $view) - { - return $this->renderer->searchAndRenderBlock($view, 'errors'); - } - - /** - * Renders views which have not already been rendered. - * - * @param array $variables An array of variables - * - * @return string The HTML markup - */ - public function rest(FormView $view, array $variables = []) - { - return $this->renderer->searchAndRenderBlock($view, 'rest', $variables); - } - - /** - * Renders a block of the template. - * - * @param string $blockName The name of the block to render - * @param array $variables The variable to pass to the template - * - * @return string The HTML markup - */ - public function block(FormView $view, $blockName, array $variables = []) - { - return $this->renderer->renderBlock($view, $blockName, $variables); - } - - /** - * Returns a CSRF token. - * - * Use this helper for CSRF protection without the overhead of creating a - * form. - * - * echo $view['form']->csrfToken('rm_user_'.$user->getId()); - * - * Check the token in your action using the same CSRF token id. - * - * // $csrfProvider being an instance of Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface - * if (!$csrfProvider->isCsrfTokenValid('rm_user_'.$user->getId(), $token)) { - * throw new \RuntimeException('CSRF attack detected.'); - * } - * - * @param string $tokenId The CSRF token id of the protected action - * - * @return string A CSRF token - * - * @throws \BadMethodCallException when no CSRF provider was injected in the constructor - */ - public function csrfToken($tokenId) - { - return $this->renderer->renderCsrfToken($tokenId); - } - - public function humanize($text) - { - return $this->renderer->humanize($text); - } - - /** - * @internal - */ - public function formEncodeCurrency($text, $widget = '') - { - if ('UTF-8' === $charset = $this->getCharset()) { - $text = htmlspecialchars($text, ENT_QUOTES | (\defined('ENT_SUBSTITUTE') ? ENT_SUBSTITUTE : 0), 'UTF-8'); - } else { - $text = htmlentities($text, ENT_QUOTES | (\defined('ENT_SUBSTITUTE') ? ENT_SUBSTITUTE : 0), 'UTF-8'); - $text = iconv('UTF-8', $charset, $text); - $widget = iconv('UTF-8', $charset, $widget); - } - - return str_replace('{{ widget }}', $widget, $text); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/RequestHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/RequestHelper.php deleted file mode 100644 index fbc054909700b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/RequestHelper.php +++ /dev/null @@ -1,77 +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\Templating\Helper; - -@trigger_error('The '.RequestHelper::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Component\Templating\Helper\Helper; - -/** - * RequestHelper provides access to the current request parameters. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class RequestHelper extends Helper -{ - protected $requestStack; - - public function __construct(RequestStack $requestStack) - { - $this->requestStack = $requestStack; - } - - /** - * Returns a parameter from the current request object. - * - * @param string $key The name of the parameter - * @param string $default A default value - * - * @return mixed - * - * @see Request::get() - */ - public function getParameter($key, $default = null) - { - return $this->getRequest()->get($key, $default); - } - - /** - * Returns the locale. - * - * @return string - */ - public function getLocale() - { - return $this->getRequest()->getLocale(); - } - - private function getRequest(): Request - { - if (!$this->requestStack->getCurrentRequest()) { - throw new \LogicException('A Request must be available.'); - } - - return $this->requestStack->getCurrentRequest(); - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'request'; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/RouterHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/RouterHelper.php deleted file mode 100644 index 0854fe3f048bd..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/RouterHelper.php +++ /dev/null @@ -1,74 +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\Templating\Helper; - -@trigger_error('The '.RouterHelper::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\Routing\Generator\UrlGeneratorInterface; -use Symfony\Component\Templating\Helper\Helper; - -/** - * RouterHelper manages links between pages in a template context. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class RouterHelper extends Helper -{ - protected $generator; - - public function __construct(UrlGeneratorInterface $router) - { - $this->generator = $router; - } - - /** - * Generates a URL reference (as an absolute or relative path) to the route with the given parameters. - * - * @param string $name The name of the route - * @param mixed $parameters An array of parameters - * @param bool $relative Whether to generate a relative or absolute path - * - * @return string The generated URL reference - * - * @see UrlGeneratorInterface - */ - public function path($name, $parameters = [], $relative = false) - { - return $this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH); - } - - /** - * Generates a URL reference (as an absolute URL or network path) to the route with the given parameters. - * - * @param string $name The name of the route - * @param mixed $parameters An array of parameters - * @param bool $schemeRelative Whether to omit the scheme in the generated URL reference - * - * @return string The generated URL reference - * - * @see UrlGeneratorInterface - */ - public function url($name, $parameters = [], $schemeRelative = false) - { - return $this->generator->generate($name, $parameters, $schemeRelative ? UrlGeneratorInterface::NETWORK_PATH : UrlGeneratorInterface::ABSOLUTE_URL); - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'router'; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/SessionHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/SessionHelper.php deleted file mode 100644 index 296387b5c46c0..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/SessionHelper.php +++ /dev/null @@ -1,85 +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\Templating\Helper; - -@trigger_error('The '.SessionHelper::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Component\HttpFoundation\Session\SessionInterface; -use Symfony\Component\Templating\Helper\Helper; - -/** - * SessionHelper provides read-only access to the session attributes. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class SessionHelper extends Helper -{ - protected $session; - protected $requestStack; - - public function __construct(RequestStack $requestStack) - { - $this->requestStack = $requestStack; - } - - /** - * Returns an attribute. - * - * @param string $name The attribute name - * @param mixed $default The default value - * - * @return mixed - */ - public function get($name, $default = null) - { - return $this->getSession()->get($name, $default); - } - - public function getFlash($name, array $default = []) - { - return $this->getSession()->getFlashBag()->get($name, $default); - } - - public function getFlashes() - { - return $this->getSession()->getFlashBag()->all(); - } - - public function hasFlash($name) - { - return $this->getSession()->getFlashBag()->has($name); - } - - private function getSession(): SessionInterface - { - if (null === $this->session) { - if (!$this->requestStack->getMasterRequest()) { - throw new \LogicException('A Request must be available.'); - } - - $this->session = $this->requestStack->getMasterRequest()->getSession(); - } - - return $this->session; - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'session'; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/StopwatchHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/StopwatchHelper.php deleted file mode 100644 index 432e7002dd048..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/StopwatchHelper.php +++ /dev/null @@ -1,52 +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\Templating\Helper; - -@trigger_error('The '.StopwatchHelper::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\Stopwatch\Stopwatch; -use Symfony\Component\Templating\Helper\Helper; - -/** - * StopwatchHelper provides methods time your PHP templates. - * - * @author Wouter J - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class StopwatchHelper extends Helper -{ - private $stopwatch; - - public function __construct(Stopwatch $stopwatch = null) - { - $this->stopwatch = $stopwatch; - } - - public function getName() - { - return 'stopwatch'; - } - - public function __call($method, $arguments = []) - { - if (null === $this->stopwatch) { - return null; - } - - if (method_exists($this->stopwatch, $method)) { - return $this->stopwatch->{$method}(...$arguments); - } - - throw new \BadMethodCallException(sprintf('Method "%s" of Stopwatch does not exist', $method)); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/TranslatorHelper.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/TranslatorHelper.php deleted file mode 100644 index b86c0da666aa2..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Helper/TranslatorHelper.php +++ /dev/null @@ -1,84 +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\Templating\Helper; - -@trigger_error('The '.TranslatorHelper::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\Templating\Helper\Helper; -use Symfony\Component\Translation\TranslatorInterface as LegacyTranslatorInterface; -use Symfony\Contracts\Translation\TranslatorInterface; -use Symfony\Contracts\Translation\TranslatorTrait; - -/** - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class TranslatorHelper extends Helper -{ - use TranslatorTrait { - getLocale as private; - setLocale as private; - trans as private doTrans; - } - - protected $translator; - - /** - * @param TranslatorInterface|null $translator - */ - public function __construct($translator = null) - { - if (null !== $translator && !$translator instanceof LegacyTranslatorInterface && !$translator instanceof TranslatorInterface) { - throw new \TypeError(sprintf('Argument 1 passed to %s() must be an instance of %s, %s given.', __METHOD__, TranslatorInterface::class, \is_object($translator) ? \get_class($translator) : \gettype($translator))); - } - $this->translator = $translator; - } - - /** - * @see TranslatorInterface::trans() - */ - public function trans($id, array $parameters = [], $domain = 'messages', $locale = null) - { - if (null === $this->translator) { - return $this->doTrans($id, $parameters, $domain, $locale); - } - - return $this->translator->trans($id, $parameters, $domain, $locale); - } - - /** - * @see TranslatorInterface::transChoice() - * @deprecated since Symfony 4.2, use the trans() method instead with a %count% parameter - */ - public function transChoice($id, $number, array $parameters = [], $domain = 'messages', $locale = null) - { - @trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2, use the trans() one instead with a "%%count%%" parameter.', __METHOD__), E_USER_DEPRECATED); - - if (null === $this->translator) { - return $this->doTrans($id, ['%count%' => $number] + $parameters, $domain, $locale); - } - if ($this->translator instanceof TranslatorInterface) { - return $this->translator->trans($id, ['%count%' => $number] + $parameters, $domain, $locale); - } - - return $this->translator->transChoice($id, $number, $parameters, $domain, $locale); - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'translator'; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/FilesystemLoader.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/FilesystemLoader.php deleted file mode 100644 index 52edeb86199fe..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/FilesystemLoader.php +++ /dev/null @@ -1,66 +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\Templating\Loader; - -@trigger_error('The '.FilesystemLoader::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\Config\FileLocatorInterface; -use Symfony\Component\Templating\Loader\LoaderInterface; -use Symfony\Component\Templating\Storage\FileStorage; -use Symfony\Component\Templating\TemplateReferenceInterface; - -/** - * FilesystemLoader is a loader that read templates from the filesystem. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class FilesystemLoader implements LoaderInterface -{ - protected $locator; - - public function __construct(FileLocatorInterface $locator) - { - $this->locator = $locator; - } - - /** - * {@inheritdoc} - */ - public function load(TemplateReferenceInterface $template) - { - try { - $file = $this->locator->locate($template); - } catch (\InvalidArgumentException $e) { - return false; - } - - return new FileStorage($file); - } - - /** - * {@inheritdoc} - */ - public function isFresh(TemplateReferenceInterface $template, $time) - { - if (false === $storage = $this->load($template)) { - return false; - } - - if (!is_readable((string) $storage)) { - return false; - } - - return filemtime((string) $storage) < $time; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/TemplateLocator.php b/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/TemplateLocator.php deleted file mode 100644 index 26f4028d363be..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/Loader/TemplateLocator.php +++ /dev/null @@ -1,88 +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\Templating\Loader; - -@trigger_error('The '.TemplateLocator::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\Config\FileLocatorInterface; -use Symfony\Component\Templating\TemplateReferenceInterface; - -/** - * TemplateLocator locates templates in bundles. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class TemplateLocator implements FileLocatorInterface -{ - protected $locator; - protected $cache; - - private $cacheHits = []; - - /** - * @param string $cacheDir The cache path - */ - public function __construct(FileLocatorInterface $locator, string $cacheDir = null) - { - if (null !== $cacheDir && file_exists($cache = $cacheDir.'/templates.php')) { - $this->cache = require $cache; - } - - $this->locator = $locator; - } - - /** - * Returns a full path for a given file. - * - * @return string The full path for the file - */ - protected function getCacheKey($template) - { - return $template->getLogicalName(); - } - - /** - * Returns a full path for a given file. - * - * @param TemplateReferenceInterface $template A template - * @param string $currentPath Unused - * @param bool $first Unused - * - * @return string The full path for the file - * - * @throws \InvalidArgumentException When the template is not an instance of TemplateReferenceInterface - * @throws \InvalidArgumentException When the template file can not be found - */ - public function locate($template, $currentPath = null, $first = true) - { - if (!$template instanceof TemplateReferenceInterface) { - throw new \InvalidArgumentException('The template must be an instance of TemplateReferenceInterface.'); - } - - $key = $this->getCacheKey($template); - - if (isset($this->cacheHits[$key])) { - return $this->cacheHits[$key]; - } - if (isset($this->cache[$key])) { - return $this->cacheHits[$key] = realpath($this->cache[$key]) ?: $this->cache[$key]; - } - - try { - return $this->cacheHits[$key] = $this->locator->locate($template->getPath(), $currentPath); - } catch (\InvalidArgumentException $e) { - throw new \InvalidArgumentException(sprintf('Unable to find template "%s" : "%s".', $template, $e->getMessage()), 0, $e); - } - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/PhpEngine.php b/src/Symfony/Bundle/FrameworkBundle/Templating/PhpEngine.php deleted file mode 100644 index 080d0b7815210..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/PhpEngine.php +++ /dev/null @@ -1,82 +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\Templating; - -@trigger_error('The '.PhpEngine::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Psr\Container\ContainerInterface; -use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\Templating\Loader\LoaderInterface; -use Symfony\Component\Templating\PhpEngine as BasePhpEngine; -use Symfony\Component\Templating\TemplateNameParserInterface; - -/** - * This engine knows how to render Symfony templates. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class PhpEngine extends BasePhpEngine implements EngineInterface -{ - protected $container; - - public function __construct(TemplateNameParserInterface $parser, ContainerInterface $container, LoaderInterface $loader, GlobalVariables $globals = null) - { - $this->container = $container; - - parent::__construct($parser, $loader); - - if (null !== $globals) { - $this->addGlobal('app', $globals); - } - } - - /** - * {@inheritdoc} - */ - public function get($name) - { - if (!isset($this->helpers[$name])) { - throw new \InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name)); - } - - if (\is_string($this->helpers[$name])) { - $this->helpers[$name] = $this->container->get($this->helpers[$name]); - $this->helpers[$name]->setCharset($this->charset); - } - - return $this->helpers[$name]; - } - - /** - * {@inheritdoc} - */ - public function setHelpers(array $helpers) - { - $this->helpers = $helpers; - } - - /** - * {@inheritdoc} - */ - public function renderResponse($view, array $parameters = [], Response $response = null) - { - if (null === $response) { - $response = new Response(); - } - - $response->setContent($this->render($view, $parameters)); - - return $response; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateFilenameParser.php b/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateFilenameParser.php deleted file mode 100644 index de383461d7f8a..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateFilenameParser.php +++ /dev/null @@ -1,49 +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\Templating; - -@trigger_error('The '.TemplateFilenameParser::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\Templating\TemplateNameParserInterface; -use Symfony\Component\Templating\TemplateReferenceInterface; - -/** - * TemplateFilenameParser converts template filenames to - * TemplateReferenceInterface instances. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class TemplateFilenameParser implements TemplateNameParserInterface -{ - /** - * {@inheritdoc} - */ - public function parse($name) - { - if ($name instanceof TemplateReferenceInterface) { - return $name; - } - - $parts = explode('/', str_replace('\\', '/', $name)); - - $elements = explode('.', array_pop($parts)); - if (3 > \count($elements)) { - return false; - } - $engine = array_pop($elements); - $format = array_pop($elements); - - return new TemplateReference('', implode('/', $parts), implode('.', $elements), $format, $engine); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php b/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php deleted file mode 100644 index ffa9a923f1f9d..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateNameParser.php +++ /dev/null @@ -1,73 +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\Templating; - -@trigger_error('The '.TemplateNameParser::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\HttpKernel\KernelInterface; -use Symfony\Component\Templating\TemplateNameParser as BaseTemplateNameParser; -use Symfony\Component\Templating\TemplateReferenceInterface; - -/** - * TemplateNameParser converts template names from the short notation - * "bundle:section:template.format.engine" to TemplateReferenceInterface - * instances. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class TemplateNameParser extends BaseTemplateNameParser -{ - protected $kernel; - protected $cache = []; - - public function __construct(KernelInterface $kernel) - { - $this->kernel = $kernel; - } - - /** - * {@inheritdoc} - */ - public function parse($name) - { - if ($name instanceof TemplateReferenceInterface) { - return $name; - } elseif (isset($this->cache[$name])) { - return $this->cache[$name]; - } - - // normalize name - $name = str_replace(':/', ':', preg_replace('#/{2,}#', '/', str_replace('\\', '/', $name))); - - if (false !== strpos($name, '..')) { - throw new \RuntimeException(sprintf('Template name "%s" contains invalid characters.', $name)); - } - - if (!preg_match('/^(?:([^:]*):([^:]*):)?(.+)\.([^\.]+)\.([^\.]+)$/', $name, $matches) || 0 === strpos($name, '@')) { - return parent::parse($name); - } - - $template = new TemplateReference($matches[1], $matches[2], $matches[3], $matches[4], $matches[5]); - - if ($template->get('bundle')) { - try { - $this->kernel->getBundle($template->get('bundle')); - } catch (\Exception $e) { - throw new \InvalidArgumentException(sprintf('Template name "%s" is not valid.', $name), 0, $e); - } - } - - return $this->cache[$name] = $template; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateReference.php b/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateReference.php deleted file mode 100644 index 3bc461ebb66e8..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/TemplateReference.php +++ /dev/null @@ -1,61 +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\Templating; - -@trigger_error('The '.TemplateReference::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\Templating\TemplateReference as BaseTemplateReference; - -/** - * Internal representation of a template. - * - * @author Victor Berchet - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class TemplateReference extends BaseTemplateReference -{ - public function __construct(string $bundle = null, string $controller = null, string $name = null, string $format = null, string $engine = null) - { - $this->parameters = [ - 'bundle' => $bundle, - 'controller' => $controller, - 'name' => $name, - 'format' => $format, - 'engine' => $engine, - ]; - } - - /** - * Returns the path to the template - * - as a path when the template is not part of a bundle - * - as a resource when the template is part of a bundle. - * - * @return string A path to the template or a resource - */ - public function getPath() - { - $controller = str_replace('\\', '/', $this->get('controller')); - - $path = (empty($controller) ? '' : $controller.'/').$this->get('name').'.'.$this->get('format').'.'.$this->get('engine'); - - return empty($this->parameters['bundle']) ? 'views/'.$path : '@'.$this->get('bundle').'/Resources/views/'.$path; - } - - /** - * {@inheritdoc} - */ - public function getLogicalName() - { - return sprintf('%s:%s:%s.%s.%s', $this->parameters['bundle'], $this->parameters['controller'], $this->parameters['name'], $this->parameters['format'], $this->parameters['engine']); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Templating/TimedPhpEngine.php b/src/Symfony/Bundle/FrameworkBundle/Templating/TimedPhpEngine.php deleted file mode 100644 index faa7c55fae63b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Templating/TimedPhpEngine.php +++ /dev/null @@ -1,52 +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\Templating; - -@trigger_error('The '.TimedPhpEngine::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Psr\Container\ContainerInterface; -use Symfony\Component\Stopwatch\Stopwatch; -use Symfony\Component\Templating\Loader\LoaderInterface; -use Symfony\Component\Templating\TemplateNameParserInterface; - -/** - * Times the time spent to render a template. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class TimedPhpEngine extends PhpEngine -{ - protected $stopwatch; - - public function __construct(TemplateNameParserInterface $parser, ContainerInterface $container, LoaderInterface $loader, Stopwatch $stopwatch, GlobalVariables $globals = null) - { - parent::__construct($parser, $container, $loader, $globals); - - $this->stopwatch = $stopwatch; - } - - /** - * {@inheritdoc} - */ - public function render($name, array $parameters = []) - { - $e = $this->stopwatch->start(sprintf('template.php (%s)', $name), 'template'); - - $ret = parent::render($name, $parameters); - - $e->stop(); - - return $ret; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Test/ForwardCompatTestTrait.php b/src/Symfony/Bundle/FrameworkBundle/Test/ForwardCompatTestTrait.php deleted file mode 100644 index 7dd933858088d..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Test/ForwardCompatTestTrait.php +++ /dev/null @@ -1,78 +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 setUp/tearDown methods - -if (method_exists(\ReflectionMethod::class, 'hasReturnType') && (new \ReflectionMethod(TestCase::class, 'tearDown'))->hasReturnType()) { - /** - * @internal - */ - trait ForwardCompatTestTrait - { - private function doSetUp(): void - { - } - - private function doTearDown(): void - { - } - - protected function setUp(): void - { - $this->doSetUp(); - } - - protected function tearDown(): void - { - $this->doTearDown(); - } - } -} else { - /** - * @internal - */ - trait ForwardCompatTestTrait - { - /** - * @return void - */ - private function doSetUp() - { - } - - /** - * @return void - */ - private function doTearDown() - { - } - - /** - * @return void - */ - protected function setUp() - { - $this->doSetUp(); - } - - /** - * @return void - */ - protected function tearDown() - { - $this->doTearDown(); - } - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Test/KernelTestCase.php b/src/Symfony/Bundle/FrameworkBundle/Test/KernelTestCase.php index a8fd09dc10121..478b3983a194d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Test/KernelTestCase.php +++ b/src/Symfony/Bundle/FrameworkBundle/Test/KernelTestCase.php @@ -23,8 +23,6 @@ */ abstract class KernelTestCase extends TestCase { - use ForwardCompatTestTrait; - protected static $class; /** @@ -41,7 +39,7 @@ abstract class KernelTestCase extends TestCase private static $kernelContainer; - private function doTearDown() + protected function tearDown(): void { static::ensureKernelShutdown(); static::$kernel = null; diff --git a/src/Symfony/Bundle/FrameworkBundle/Test/TestContainer.php b/src/Symfony/Bundle/FrameworkBundle/Test/TestContainer.php index 458720268ddfe..a0dd8475358d5 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Test/TestContainer.php +++ b/src/Symfony/Bundle/FrameworkBundle/Test/TestContainer.php @@ -59,7 +59,7 @@ public function getParameterBag(): ParameterBagInterface /** * {@inheritdoc} */ - public function getParameter($name) + public function getParameter(string $name) { return $this->getPublicContainer()->getParameter($name); } @@ -67,7 +67,7 @@ public function getParameter($name) /** * {@inheritdoc} */ - public function hasParameter($name): bool + public function hasParameter(string $name): bool { return $this->getPublicContainer()->hasParameter($name); } @@ -75,7 +75,7 @@ public function hasParameter($name): bool /** * {@inheritdoc} */ - public function setParameter($name, $value) + public function setParameter(string $name, $value) { $this->getPublicContainer()->setParameter($name, $value); } @@ -83,7 +83,7 @@ public function setParameter($name, $value) /** * {@inheritdoc} */ - public function set($id, $service) + public function set(string $id, $service) { $this->getPublicContainer()->set($id, $service); } @@ -98,10 +98,8 @@ public function has($id): bool /** * {@inheritdoc} - * - * @return object|null */ - public function get($id, $invalidBehavior = /* self::EXCEPTION_ON_INVALID_REFERENCE */ 1) + public function get($id, int $invalidBehavior = /* self::EXCEPTION_ON_INVALID_REFERENCE */ 1): ?object { return $this->getPrivateContainer()->has($id) ? $this->getPrivateContainer()->get($id) : $this->getPublicContainer()->get($id, $invalidBehavior); } @@ -109,7 +107,7 @@ public function get($id, $invalidBehavior = /* self::EXCEPTION_ON_INVALID_REFERE /** * {@inheritdoc} */ - public function initialized($id): bool + public function initialized(string $id): bool { return $this->getPublicContainer()->initialized($id); } diff --git a/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php b/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php index afdfc876f71c2..4935dd8098598 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php +++ b/src/Symfony/Bundle/FrameworkBundle/Test/WebTestCase.php @@ -21,11 +21,10 @@ */ abstract class WebTestCase extends KernelTestCase { - use ForwardCompatTestTrait; use WebTestAssertionsTrait; use MailerAssertionsTrait; - private function doTearDown() + protected function tearDown(): void { parent::tearDown(); self::getClient(null); @@ -42,7 +41,7 @@ private function doTearDown() protected static function createClient(array $options = [], array $server = []) { if (static::$booted) { - @trigger_error(sprintf('Calling "%s()" while a kernel has been booted is deprecated since Symfony 4.4 and will throw in 5.0, ensure the kernel is shut down before calling the method.', __METHOD__), E_USER_DEPRECATED); + throw new \LogicException(sprintf('Booting the kernel before calling %s() is not supported, the kernel should only be booted once.', __METHOD__)); } $kernel = static::bootKernel($options); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/AnnotationsCacheWarmerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/AnnotationsCacheWarmerTest.php index ca90187a8d998..9c3c005414250 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/AnnotationsCacheWarmerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/AnnotationsCacheWarmerTest.php @@ -123,7 +123,7 @@ public function testClassAutoloadExceptionWithUnrelatedException() /** * @return MockObject|Reader */ - private function getReadOnlyReader() + private function getReadOnlyReader(): object { $readerMock = $this->getMockBuilder('Doctrine\Common\Annotations\Reader')->getMock(); $readerMock->expects($this->exactly(0))->method('getClassAnnotations'); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/RouterCacheWarmerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/RouterCacheWarmerTest.php index 93dbd1a69e220..43e8a8123bd44 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/RouterCacheWarmerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/RouterCacheWarmerTest.php @@ -32,10 +32,6 @@ public function testWarmUpWithWarmebleInterface() $this->addToAssertionCount(1); } - /** - * @expectedDeprecation Passing a Symfony\Component\Routing\RouterInterface without implementing Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface is deprecated since Symfony 4.1. - * @group legacy - */ public function testWarmUpWithoutWarmebleInterface() { $containerMock = $this->getMockBuilder(ContainerInterface::class)->setMethods(['get', 'has'])->getMock(); @@ -43,6 +39,8 @@ public function testWarmUpWithoutWarmebleInterface() $routerMock = $this->getMockBuilder(testRouterInterfaceWithoutWarmebleInterface::class)->setMethods(['match', 'generate', 'getContext', 'setContext', 'getRouteCollection'])->getMock(); $containerMock->expects($this->any())->method('get')->with('router')->willReturn($routerMock); $routerCacheWarmer = new RouterCacheWarmer($containerMock); + $this->expectException(\LogicException::class); + $this->expectExceptionMessage('cannot be warmed up because it does not implement Symfony\Component\HttpKernel\CacheWarmer\WarmableInterface'); $routerCacheWarmer->warmUp('/tmp'); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/SerializerCacheWarmerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/SerializerCacheWarmerTest.php index f4febfe8ef9ec..ce303cf3e060d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/SerializerCacheWarmerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/SerializerCacheWarmerTest.php @@ -15,7 +15,6 @@ use Symfony\Bundle\FrameworkBundle\Tests\TestCase; use Symfony\Component\Cache\Adapter\NullAdapter; use Symfony\Component\Cache\Adapter\PhpArrayAdapter; -use Symfony\Component\Serializer\Mapping\Factory\CacheClassMetadataFactory; use Symfony\Component\Serializer\Mapping\Loader\XmlFileLoader; use Symfony\Component\Serializer\Mapping\Loader\YamlFileLoader; @@ -23,10 +22,6 @@ class SerializerCacheWarmerTest extends TestCase { public function testWarmUp() { - 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.'); - } - $loaders = [ new XmlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/person.xml'), new YamlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/author.yml'), @@ -48,10 +43,6 @@ public function testWarmUp() public function testWarmUpWithoutLoader() { - 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.'); - } - $file = sys_get_temp_dir().'/cache-serializer-without-loader.php'; @unlink($file); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/TemplateFinderTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/TemplateFinderTest.php deleted file mode 100644 index 52b8dfad9dfbd..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/TemplateFinderTest.php +++ /dev/null @@ -1,60 +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\Tests\CacheWarmer; - -use Symfony\Bundle\FrameworkBundle\CacheWarmer\TemplateFinder; -use Symfony\Bundle\FrameworkBundle\Templating\TemplateFilenameParser; -use Symfony\Bundle\FrameworkBundle\Tests\Fixtures\BaseBundle\BaseBundle; -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; - -/** - * @group legacy - */ -class TemplateFinderTest extends TestCase -{ - public function testFindAllTemplates() - { - $kernel = $this - ->getMockBuilder('Symfony\Component\HttpKernel\Kernel') - ->disableOriginalConstructor() - ->getMock() - ; - - $kernel - ->expects($this->any()) - ->method('getBundle') - ; - - $kernel - ->expects($this->once()) - ->method('getBundles') - ->willReturn(['BaseBundle' => new BaseBundle()]) - ; - - $parser = new TemplateFilenameParser(); - - $finder = new TemplateFinder($kernel, $parser, __DIR__.'/../Fixtures/Resources'); - - $templates = array_map( - function ($template) { return $template->getLogicalName(); }, - $finder->findAllTemplates() - ); - - $this->assertCount(7, $templates, '->findAllTemplates() find all templates in the bundles and global folders'); - $this->assertContains('BaseBundle::base.format.engine', $templates); - $this->assertContains('BaseBundle::this.is.a.template.format.engine', $templates); - $this->assertContains('BaseBundle:controller:base.format.engine', $templates); - $this->assertContains('BaseBundle:controller:custom.format.engine', $templates); - $this->assertContains('::this.is.a.template.format.engine', $templates); - $this->assertContains('::resource.format.engine', $templates); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/TemplatePathsCacheWarmerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/TemplatePathsCacheWarmerTest.php deleted file mode 100644 index f4853162d2f09..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/CacheWarmer/TemplatePathsCacheWarmerTest.php +++ /dev/null @@ -1,105 +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\Tests\CacheWarmer; - -use Symfony\Bundle\FrameworkBundle\CacheWarmer\TemplateFinderInterface; -use Symfony\Bundle\FrameworkBundle\CacheWarmer\TemplatePathsCacheWarmer; -use Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator; -use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; -use Symfony\Component\Config\FileLocator; -use Symfony\Component\Filesystem\Filesystem; - -/** - * @group legacy - */ -class TemplatePathsCacheWarmerTest extends TestCase -{ - /** @var Filesystem */ - private $filesystem; - - /** @var TemplateFinderInterface */ - private $templateFinder; - - /** @var FileLocator */ - private $fileLocator; - - /** @var TemplateLocator */ - private $templateLocator; - - private $tmpDir; - - protected function setUp(): void - { - $this->templateFinder = $this - ->getMockBuilder(TemplateFinderInterface::class) - ->setMethods(['findAllTemplates']) - ->getMock(); - - $this->fileLocator = $this - ->getMockBuilder(FileLocator::class) - ->setMethods(['locate']) - ->setConstructorArgs(['/path/to/fallback']) - ->getMock(); - - $this->templateLocator = new TemplateLocator($this->fileLocator); - - $this->tmpDir = sys_get_temp_dir().\DIRECTORY_SEPARATOR.uniqid('cache_template_paths_', true); - - $this->filesystem = new Filesystem(); - $this->filesystem->mkdir($this->tmpDir); - } - - protected function tearDown(): void - { - $this->filesystem->remove($this->tmpDir); - } - - public function testWarmUp() - { - $template = new TemplateReference('bundle', 'controller', 'name', 'format', 'engine'); - - $this->templateFinder - ->expects($this->once()) - ->method('findAllTemplates') - ->willReturn([$template]); - - $this->fileLocator - ->expects($this->once()) - ->method('locate') - ->with($template->getPath()) - ->willReturn(\dirname($this->tmpDir).'/path/to/template.html.twig'); - - $warmer = new TemplatePathsCacheWarmer($this->templateFinder, $this->templateLocator); - $warmer->warmUp($this->tmpDir); - - $this->assertFileEquals(__DIR__.'/../Fixtures/TemplatePathsCache/templates.php', $this->tmpDir.'/templates.php'); - } - - public function testWarmUpEmpty() - { - $this->templateFinder - ->expects($this->once()) - ->method('findAllTemplates') - ->willReturn([]); - - $this->fileLocator - ->expects($this->never()) - ->method('locate'); - - $warmer = new TemplatePathsCacheWarmer($this->templateFinder, $this->templateLocator); - $warmer->warmUp($this->tmpDir); - - $this->assertFileExists($this->tmpDir.'/templates.php'); - $this->assertSame(file_get_contents(__DIR__.'/../Fixtures/TemplatePathsCache/templates-empty.php'), file_get_contents($this->tmpDir.'/templates.php')); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/Fixture/TestAppKernel.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/Fixture/TestAppKernel.php index d6a58798c1369..678d573586f3a 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/Fixture/TestAppKernel.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CacheClearCommand/Fixture/TestAppKernel.php @@ -36,13 +36,6 @@ public function registerContainerConfiguration(LoaderInterface $loader) $loader->load(__DIR__.\DIRECTORY_SEPARATOR.'config.yml'); } - public function setAnnotatedClassCache(array $annotatedClasses) - { - $annotatedClasses = array_diff($annotatedClasses, ['Symfony\Bundle\WebProfilerBundle\Controller\ExceptionController', 'Symfony\Bundle\TwigBundle\Controller\ExceptionController', 'Symfony\Bundle\TwigBundle\Controller\PreviewErrorController']); - - parent::setAnnotatedClassCache($annotatedClasses); - } - protected function build(ContainerBuilder $container) { $container->register('logger', NullLogger::class); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePoolDeleteCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePoolDeleteCommandTest.php index aa70e4ed80520..42981c41484f1 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePoolDeleteCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePoolDeleteCommandTest.php @@ -86,7 +86,7 @@ public function testCommandDeleteFailed() /** * @return MockObject|KernelInterface */ - private function getKernel() + private function getKernel(): object { $container = $this ->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePruneCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePruneCommandTest.php index 251e8f33402f5..4df5fc024c235 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePruneCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/CachePruneCommandTest.php @@ -52,7 +52,7 @@ private function getEmptyRewindableGenerator(): RewindableGenerator /** * @return MockObject|KernelInterface */ - private function getKernel() + private function getKernel(): object { $container = $this ->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface') @@ -78,7 +78,7 @@ private function getKernel() /** * @return MockObject|PruneableInterface */ - private function getPruneableInterfaceMock() + private function getPruneableInterfaceMock(): object { $pruneable = $this ->getMockBuilder(PruneableInterface::class) diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php index b71931ea1605d..50f1b33ea05e1 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationDebugCommandTest.php @@ -17,7 +17,6 @@ use Symfony\Component\Console\Tester\CommandTester; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\Filesystem\Filesystem; -use Symfony\Component\HttpKernel; class TranslationDebugCommandTest extends TestCase { @@ -65,23 +64,6 @@ public function testDebugDefaultDirectory() $this->assertRegExp('/unused/', $tester->getDisplay()); } - /** - * @group legacy - * @expectedDeprecation Storing translations in the "%ssf_translation%s/Resources/translations" directory is deprecated since Symfony 4.2, use the "%ssf_translation%s/translations" directory instead. - * @expectedDeprecation Loading Twig templates from the "%ssf_translation%s/Resources/views" directory is deprecated since Symfony 4.2, use the "%ssf_translation%s/templates" directory instead. - */ - public function testDebugLegacyDefaultDirectory() - { - $this->fs->mkdir($this->translationDir.'/Resources/translations'); - $this->fs->mkdir($this->translationDir.'/Resources/views'); - - $tester = $this->createCommandTester(['foo' => 'foo'], ['bar' => 'bar']); - $tester->execute(['locale' => 'en']); - - $this->assertRegExp('/missing/', $tester->getDisplay()); - $this->assertRegExp('/unused/', $tester->getDisplay()); - } - public function testDebugDefaultRootDirectory() { $this->fs->remove($this->translationDir); @@ -176,12 +158,6 @@ function ($path, $catalogue) use ($loadedMessages) { ['foo', $this->getBundle($this->translationDir)], ['test', $this->getBundle('test')], ]; - if (HttpKernel\Kernel::VERSION_ID < 40000) { - $returnValues = [ - ['foo', true, $this->getBundle($this->translationDir)], - ['test', true, $this->getBundle('test')], - ]; - } $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock(); $kernel ->expects($this->any()) @@ -195,8 +171,6 @@ function ($path, $catalogue) use ($loadedMessages) { ->willReturn([]); $container = new Container(); - $container->setParameter('kernel.root_dir', $this->translationDir); - $kernel ->expects($this->any()) ->method('getContainer') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationUpdateCommandTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationUpdateCommandTest.php index 856ba6408e8ab..f256870de6a55 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationUpdateCommandTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Command/TranslationUpdateCommandTest.php @@ -104,23 +104,6 @@ public function testWriteMessagesInRootDirectory() $this->assertRegExp('/Translation files were successfully updated./', $tester->getDisplay()); } - /** - * @group legacy - * @expectedDeprecation Storing translations in the "%ssf_translation%s/Resources/translations" directory is deprecated since Symfony 4.2, use the "%ssf_translation%s/translations" directory instead. - * @expectedDeprecation Storing templates in the "%ssf_translation%s/Resources/views" directory is deprecated since Symfony 4.2, use the "%ssf_translation%s/templates" directory instead. - */ - public function testWriteMessagesInLegacyRootDirectory() - { - $this->fs->remove($this->translationDir); - $this->translationDir = sys_get_temp_dir().'/'.uniqid('sf_translation', true); - $this->fs->mkdir($this->translationDir.'/Resources/translations'); - $this->fs->mkdir($this->translationDir.'/Resources/views'); - - $tester = $this->createCommandTester(['messages' => ['foo' => 'foo']]); - $tester->execute(['command' => 'translation:update', 'locale' => 'en', '--force' => true]); - $this->assertRegExp('/Translation files were successfully updated./', $tester->getDisplay()); - } - public function testWriteMessagesForSpecificDomain() { $tester = $this->createCommandTester(['messages' => ['foo' => 'foo'], 'mydomain' => ['bar' => 'bar']]); @@ -190,12 +173,6 @@ function ($path, $catalogue) use ($loadedMessages) { ['foo', $this->getBundle($this->translationDir)], ['test', $this->getBundle('test')], ]; - if (HttpKernel\Kernel::VERSION_ID < 40000) { - $returnValues = [ - ['foo', true, $this->getBundle($this->translationDir)], - ['test', true, $this->getBundle('test')], - ]; - } $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock(); $kernel ->expects($this->any()) @@ -209,7 +186,6 @@ function ($path, $catalogue) use ($loadedMessages) { ->willReturn([]); $container = new Container(); - $container->setParameter('kernel.root_dir', $this->translationDir); $kernel ->expects($this->any()) ->method('getContainer') diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Console/ApplicationTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Console/ApplicationTest.php index 90ecc1ab3e221..927556faf3a68 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Console/ApplicationTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Console/ApplicationTest.php @@ -104,29 +104,6 @@ public function testBundleCommandCanBeFoundByAlias() $this->assertSame($command, $application->find('alias')); } - /** - * @group legacy - * @expectedDeprecation The "Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand" class is deprecated since Symfony 4.2, use "Symfony\Component\Console\Command\Command" with dependency injection instead. - */ - public function testBundleCommandsHaveRightContainer() - { - $command = $this->getMockForAbstractClass('Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand', ['foo'], '', true, true, true, ['setContainer']); - $command->setCode(function () {}); - $command->expects($this->exactly(2))->method('setContainer'); - - $application = new Application($this->getKernel([], true)); - $application->setAutoExit(false); - $application->setCatchExceptions(false); - $application->add($command); - $tester = new ApplicationTester($application); - - // set container is called here - $tester->run(['command' => 'foo']); - - // as the container might have change between two runs, setContainer must called again - $tester->run(['command' => 'foo']); - } - public function testBundleCommandCanOverriddeAPreExistingCommandWithTheSameName() { $command = new Command('example'); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php index 27eed3fbface1..ca1d7ef011104 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/AbstractControllerTest.php @@ -11,13 +11,28 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Controller; -use Psr\Container\ContainerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; +use Symfony\Bundle\FrameworkBundle\Tests\TestCase; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\ParameterBag\ContainerBag; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; +use Symfony\Component\Form\Form; +use Symfony\Component\Form\FormConfigInterface; +use Symfony\Component\HttpFoundation\BinaryFileResponse; +use Symfony\Component\HttpFoundation\File\File; +use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Request; +use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Response; +use Symfony\Component\HttpFoundation\ResponseHeaderBag; +use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; +use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; +use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; +use Symfony\Component\Security\Core\User\User; +use Symfony\Component\Serializer\SerializerInterface; +use Symfony\Component\WebLink\Link; -class AbstractControllerTest extends ControllerTraitTest +class AbstractControllerTest extends TestCase { protected function createController() { @@ -37,7 +52,6 @@ public function testSubscribedServices() 'serializer' => '?Symfony\\Component\\Serializer\\SerializerInterface', 'session' => '?Symfony\\Component\\HttpFoundation\\Session\\SessionInterface', 'security.authorization_checker' => '?Symfony\\Component\\Security\\Core\\Authorization\\AuthorizationCheckerInterface', - 'templating' => '?Symfony\\Component\\Templating\\EngineInterface', 'twig' => '?Twig\\Environment', 'doctrine' => '?Doctrine\\Common\\Persistence\\ManagerRegistry', 'form.factory' => '?Symfony\\Component\\Form\\FormFactoryInterface', @@ -77,47 +91,470 @@ public function testMissingParameterBag() $controller->getParameter('foo'); } -} -class TestAbstractController extends AbstractController -{ - private $throwOnUnexpectedService; + public function testForward() + { + $request = Request::create('/'); + $request->setLocale('fr'); + $request->setRequestFormat('xml'); + + $requestStack = new RequestStack(); + $requestStack->push($request); + + $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(); + $kernel->expects($this->once())->method('handle')->willReturnCallback(function (Request $request) { + return new Response($request->getRequestFormat().'--'.$request->getLocale()); + }); + + $container = new Container(); + $container->set('request_stack', $requestStack); + $container->set('http_kernel', $kernel); + + $controller = $this->createController(); + $controller->setContainer($container); + + $response = $controller->forward('a_controller'); + $this->assertEquals('xml--fr', $response->getContent()); + } + + public function testGetUser() + { + $user = new User('user', 'pass'); + $token = new UsernamePasswordToken($user, 'pass', 'default', ['ROLE_USER']); + + $controller = $this->createController(); + $controller->setContainer($this->getContainerWithTokenStorage($token)); + + $this->assertSame($controller->getUser(), $user); + } + + public function testGetUserAnonymousUserConvertedToNull() + { + $token = new AnonymousToken('default', 'anon.'); + + $controller = $this->createController(); + $controller->setContainer($this->getContainerWithTokenStorage($token)); + + $this->assertNull($controller->getUser()); + } + + public function testGetUserWithEmptyTokenStorage() + { + $controller = $this->createController(); + $controller->setContainer($this->getContainerWithTokenStorage(null)); + + $this->assertNull($controller->getUser()); + } + + public function testGetUserWithEmptyContainer() + { + $this->expectException('LogicException'); + $this->expectExceptionMessage('The SecurityBundle is not registered in your application.'); + + $controller = $this->createController(); + $controller->setContainer(new Container()); + + $controller->getUser(); + } + + /** + * @param $token + */ + private function getContainerWithTokenStorage($token = null): Container + { + $tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage')->getMock(); + $tokenStorage + ->expects($this->once()) + ->method('getToken') + ->willReturn($token); + + $container = new Container(); + $container->set('security.token_storage', $tokenStorage); + + return $container; + } + + public function testJson() + { + $controller = $this->createController(); + $controller->setContainer(new Container()); + + $response = $controller->json([]); + $this->assertInstanceOf(JsonResponse::class, $response); + $this->assertEquals('[]', $response->getContent()); + } + + public function testJsonWithSerializer() + { + $container = new Container(); + + $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer + ->expects($this->once()) + ->method('serialize') + ->with([], 'json', ['json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS]) + ->willReturn('[]'); + + $container->set('serializer', $serializer); + + $controller = $this->createController(); + $controller->setContainer($container); + + $response = $controller->json([]); + $this->assertInstanceOf(JsonResponse::class, $response); + $this->assertEquals('[]', $response->getContent()); + } + + public function testJsonWithSerializerContextOverride() + { + $container = new Container(); + + $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); + $serializer + ->expects($this->once()) + ->method('serialize') + ->with([], 'json', ['json_encode_options' => 0, 'other' => 'context']) + ->willReturn('[]'); + + $container->set('serializer', $serializer); - public function __construct($throwOnUnexpectedService = true) + $controller = $this->createController(); + $controller->setContainer($container); + + $response = $controller->json([], 200, [], ['json_encode_options' => 0, 'other' => 'context']); + $this->assertInstanceOf(JsonResponse::class, $response); + $this->assertEquals('[]', $response->getContent()); + $response->setEncodingOptions(JSON_FORCE_OBJECT); + $this->assertEquals('{}', $response->getContent()); + } + + public function testFile() { - $this->throwOnUnexpectedService = $throwOnUnexpectedService; + $container = new Container(); + $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(); + $container->set('http_kernel', $kernel); + + $controller = $this->createController(); + $controller->setContainer($container); + + /* @var BinaryFileResponse $response */ + $response = $controller->file(new File(__FILE__)); + $this->assertInstanceOf(BinaryFileResponse::class, $response); + $this->assertSame(200, $response->getStatusCode()); + if ($response->headers->get('content-type')) { + $this->assertSame('text/x-php', $response->headers->get('content-type')); + } + $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); + $this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition')); } - public function __call(string $method, array $arguments) + public function testFileAsInline() { - return $this->$method(...$arguments); + $controller = $this->createController(); + + /* @var BinaryFileResponse $response */ + $response = $controller->file(new File(__FILE__), null, ResponseHeaderBag::DISPOSITION_INLINE); + + $this->assertInstanceOf(BinaryFileResponse::class, $response); + $this->assertSame(200, $response->getStatusCode()); + if ($response->headers->get('content-type')) { + $this->assertSame('text/x-php', $response->headers->get('content-type')); + } + $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition')); + $this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition')); } - public function setContainer(ContainerInterface $container): ?ContainerInterface + public function testFileWithOwnFileName() { - if (!$this->throwOnUnexpectedService) { - return parent::setContainer($container); + $controller = $this->createController(); + + /* @var BinaryFileResponse $response */ + $fileName = 'test.php'; + $response = $controller->file(new File(__FILE__), $fileName); + + $this->assertInstanceOf(BinaryFileResponse::class, $response); + $this->assertSame(200, $response->getStatusCode()); + if ($response->headers->get('content-type')) { + $this->assertSame('text/x-php', $response->headers->get('content-type')); } + $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); + $this->assertStringContainsString($fileName, $response->headers->get('content-disposition')); + } - $expected = self::getSubscribedServices(); - - foreach ($container->getServiceIds() as $id) { - if ('service_container' === $id) { - continue; - } - if (!isset($expected[$id])) { - throw new \UnexpectedValueException(sprintf('Service "%s" is not expected, as declared by %s::getSubscribedServices()', $id, AbstractController::class)); - } - $type = substr($expected[$id], 1); - if (!$container->get($id) instanceof $type) { - throw new \UnexpectedValueException(sprintf('Service "%s" is expected to be an instance of "%s", as declared by %s::getSubscribedServices()', $id, $type, AbstractController::class)); - } + public function testFileWithOwnFileNameAsInline() + { + $controller = $this->createController(); + + /* @var BinaryFileResponse $response */ + $fileName = 'test.php'; + $response = $controller->file(new File(__FILE__), $fileName, ResponseHeaderBag::DISPOSITION_INLINE); + + $this->assertInstanceOf(BinaryFileResponse::class, $response); + $this->assertSame(200, $response->getStatusCode()); + if ($response->headers->get('content-type')) { + $this->assertSame('text/x-php', $response->headers->get('content-type')); } + $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition')); + $this->assertStringContainsString($fileName, $response->headers->get('content-disposition')); + } + + public function testFileFromPath() + { + $controller = $this->createController(); + + /* @var BinaryFileResponse $response */ + $response = $controller->file(__FILE__); + + $this->assertInstanceOf(BinaryFileResponse::class, $response); + $this->assertSame(200, $response->getStatusCode()); + if ($response->headers->get('content-type')) { + $this->assertSame('text/x-php', $response->headers->get('content-type')); + } + $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); + $this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition')); + } + + public function testFileFromPathWithCustomizedFileName() + { + $controller = $this->createController(); + + /* @var BinaryFileResponse $response */ + $response = $controller->file(__FILE__, 'test.php'); + + $this->assertInstanceOf(BinaryFileResponse::class, $response); + $this->assertSame(200, $response->getStatusCode()); + if ($response->headers->get('content-type')) { + $this->assertSame('text/x-php', $response->headers->get('content-type')); + } + $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); + $this->assertStringContainsString('test.php', $response->headers->get('content-disposition')); + } + + public function testFileWhichDoesNotExist() + { + $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); + + $controller = $this->createController(); + + $controller->file('some-file.txt', 'test.php'); + } + + public function testIsGranted() + { + $authorizationChecker = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface')->getMock(); + $authorizationChecker->expects($this->once())->method('isGranted')->willReturn(true); + + $container = new Container(); + $container->set('security.authorization_checker', $authorizationChecker); + + $controller = $this->createController(); + $controller->setContainer($container); + + $this->assertTrue($controller->isGranted('foo')); + } + + public function testdenyAccessUnlessGranted() + { + $this->expectException('Symfony\Component\Security\Core\Exception\AccessDeniedException'); - return parent::setContainer($container); + $authorizationChecker = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface')->getMock(); + $authorizationChecker->expects($this->once())->method('isGranted')->willReturn(false); + + $container = new Container(); + $container->set('security.authorization_checker', $authorizationChecker); + + $controller = $this->createController(); + $controller->setContainer($container); + + $controller->denyAccessUnlessGranted('foo'); + } + + public function testRenderViewTwig() + { + $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); + $twig->expects($this->once())->method('render')->willReturn('bar'); + + $container = new Container(); + $container->set('twig', $twig); + + $controller = $this->createController(); + $controller->setContainer($container); + + $this->assertEquals('bar', $controller->renderView('foo')); + } + + public function testRenderTwig() + { + $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); + $twig->expects($this->once())->method('render')->willReturn('bar'); + + $container = new Container(); + $container->set('twig', $twig); + + $controller = $this->createController(); + $controller->setContainer($container); + + $this->assertEquals('bar', $controller->render('foo')->getContent()); + } + + public function testStreamTwig() + { + $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); + + $container = new Container(); + $container->set('twig', $twig); + + $controller = $this->createController(); + $controller->setContainer($container); + + $this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $controller->stream('foo')); + } + + public function testRedirectToRoute() + { + $router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock(); + $router->expects($this->once())->method('generate')->willReturn('/foo'); + + $container = new Container(); + $container->set('router', $router); + + $controller = $this->createController(); + $controller->setContainer($container); + $response = $controller->redirectToRoute('foo'); + + $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); + $this->assertSame('/foo', $response->getTargetUrl()); + $this->assertSame(302, $response->getStatusCode()); + } + + /** + * @runInSeparateProcess + */ + public function testAddFlash() + { + $flashBag = new FlashBag(); + $session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Session')->getMock(); + $session->expects($this->once())->method('getFlashBag')->willReturn($flashBag); + + $container = new Container(); + $container->set('session', $session); + + $controller = $this->createController(); + $controller->setContainer($container); + $controller->addFlash('foo', 'bar'); + + $this->assertSame(['bar'], $flashBag->get('foo')); + } + + public function testCreateAccessDeniedException() + { + $controller = $this->createController(); + + $this->assertInstanceOf('Symfony\Component\Security\Core\Exception\AccessDeniedException', $controller->createAccessDeniedException()); + } + + public function testIsCsrfTokenValid() + { + $tokenManager = $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock(); + $tokenManager->expects($this->once())->method('isTokenValid')->willReturn(true); + + $container = new Container(); + $container->set('security.csrf.token_manager', $tokenManager); + + $controller = $this->createController(); + $controller->setContainer($container); + + $this->assertTrue($controller->isCsrfTokenValid('foo', 'bar')); + } + + public function testGenerateUrl() + { + $router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock(); + $router->expects($this->once())->method('generate')->willReturn('/foo'); + + $container = new Container(); + $container->set('router', $router); + + $controller = $this->createController(); + $controller->setContainer($container); + + $this->assertEquals('/foo', $controller->generateUrl('foo')); + } + + public function testRedirect() + { + $controller = $this->createController(); + $response = $controller->redirect('http://dunglas.fr', 301); + + $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); + $this->assertSame('http://dunglas.fr', $response->getTargetUrl()); + $this->assertSame(301, $response->getStatusCode()); } - public function fooAction() + public function testCreateNotFoundException() { + $controller = $this->createController(); + + $this->assertInstanceOf('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', $controller->createNotFoundException()); + } + + public function testCreateForm() + { + $form = new Form($this->getMockBuilder(FormConfigInterface::class)->getMock()); + + $formFactory = $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock(); + $formFactory->expects($this->once())->method('create')->willReturn($form); + + $container = new Container(); + $container->set('form.factory', $formFactory); + + $controller = $this->createController(); + $controller->setContainer($container); + + $this->assertEquals($form, $controller->createForm('foo')); + } + + public function testCreateFormBuilder() + { + $formBuilder = $this->getMockBuilder('Symfony\Component\Form\FormBuilderInterface')->getMock(); + + $formFactory = $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock(); + $formFactory->expects($this->once())->method('createBuilder')->willReturn($formBuilder); + + $container = new Container(); + $container->set('form.factory', $formFactory); + + $controller = $this->createController(); + $controller->setContainer($container); + + $this->assertEquals($formBuilder, $controller->createFormBuilder('foo')); + } + + public function testGetDoctrine() + { + $doctrine = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock(); + + $container = new Container(); + $container->set('doctrine', $doctrine); + + $controller = $this->createController(); + $controller->setContainer($container); + + $this->assertEquals($doctrine, $controller->getDoctrine()); + } + + public function testAddLink() + { + $request = new Request(); + $link1 = new Link('mercure', 'https://demo.mercure.rocks'); + $link2 = new Link('self', 'https://example.com/foo'); + + $controller = $this->createController(); + $controller->addLink($request, $link1); + $controller->addLink($request, $link2); + + $links = $request->attributes->get('_links')->getLinks(); + $this->assertContains($link1, $links); + $this->assertContains($link2, $links); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php deleted file mode 100644 index f8eccbb75e84b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerNameParserTest.php +++ /dev/null @@ -1,189 +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\Tests\Controller; - -use Composer\Autoload\ClassLoader; -use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser; -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; -use Symfony\Component\HttpKernel\Kernel; - -/** - * @group legacy - */ -class ControllerNameParserTest extends TestCase -{ - protected $loader; - - protected function setUp(): void - { - $this->loader = new ClassLoader(); - $this->loader->add('TestBundle', __DIR__.'/../Fixtures'); - $this->loader->add('TestApplication', __DIR__.'/../Fixtures'); - $this->loader->register(); - } - - protected function tearDown(): void - { - $this->loader->unregister(); - $this->loader = null; - } - - public function testParse() - { - $parser = $this->createParser(); - - $this->assertEquals('TestBundle\FooBundle\Controller\DefaultController::indexAction', $parser->parse('FooBundle:Default:index'), '->parse() converts a short a:b:c notation string to a class::method string'); - $this->assertEquals('TestBundle\FooBundle\Controller\Sub\DefaultController::indexAction', $parser->parse('FooBundle:Sub\Default:index'), '->parse() converts a short a:b:c notation string to a class::method string'); - $this->assertEquals('TestBundle\Sensio\Cms\FooBundle\Controller\DefaultController::indexAction', $parser->parse('SensioCmsFooBundle:Default:index'), '->parse() converts a short a:b:c notation string to a class::method string'); - $this->assertEquals('TestBundle\FooBundle\Controller\Test\DefaultController::indexAction', $parser->parse('FooBundle:Test\\Default:index'), '->parse() converts a short a:b:c notation string to a class::method string'); - $this->assertEquals('TestBundle\FooBundle\Controller\Test\DefaultController::indexAction', $parser->parse('FooBundle:Test/Default:index'), '->parse() converts a short a:b:c notation string to a class::method string'); - - try { - $parser->parse('foo:'); - $this->fail('->parse() throws an \InvalidArgumentException if the controller is not an a:b:c string'); - } catch (\Exception $e) { - $this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an a:b:c string'); - } - } - - public function testBuild() - { - $parser = $this->createParser(); - - $this->assertEquals('FoooooBundle:Default:index', $parser->build('TestBundle\FooBundle\Controller\DefaultController::indexAction'), '->parse() converts a class::method string to a short a:b:c notation string'); - $this->assertEquals('FoooooBundle:Sub\Default:index', $parser->build('TestBundle\FooBundle\Controller\Sub\DefaultController::indexAction'), '->parse() converts a class::method string to a short a:b:c notation string'); - - try { - $parser->build('TestBundle\FooBundle\Controller\DefaultController::index'); - $this->fail('->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string'); - } catch (\Exception $e) { - $this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string'); - } - - try { - $parser->build('TestBundle\FooBundle\Controller\Default::indexAction'); - $this->fail('->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string'); - } catch (\Exception $e) { - $this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string'); - } - - try { - $parser->build('Foo\Controller\DefaultController::indexAction'); - $this->fail('->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string'); - } catch (\Exception $e) { - $this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws an \InvalidArgumentException if the controller is not an aController::cAction string'); - } - } - - /** - * @dataProvider getMissingControllersTest - */ - public function testMissingControllers($name) - { - $parser = $this->createParser(); - - try { - $parser->parse($name); - $this->fail('->parse() throws a \InvalidArgumentException if the class is found but does not exist'); - } catch (\Exception $e) { - $this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws a \InvalidArgumentException if the class is found but does not exist'); - } - } - - public function getMissingControllersTest() - { - // a normal bundle - $bundles = [ - ['FooBundle:Fake:index'], - ]; - - // a bundle with children - if (Kernel::VERSION_ID < 40000) { - $bundles[] = ['SensioFooBundle:Fake:index']; - } - - return $bundles; - } - - /** - * @dataProvider getInvalidBundleNameTests - */ - public function testInvalidBundleName($bundleName, $suggestedBundleName) - { - $parser = $this->createParser(); - - try { - $parser->parse($bundleName); - $this->fail('->parse() throws a \InvalidArgumentException if the bundle does not exist'); - } catch (\Exception $e) { - $this->assertInstanceOf('\InvalidArgumentException', $e, '->parse() throws a \InvalidArgumentException if the bundle does not exist'); - - if (false === $suggestedBundleName) { - // make sure we don't have a suggestion - $this->assertStringNotContainsString('Did you mean', $e->getMessage()); - } else { - $this->assertStringContainsString(sprintf('Did you mean "%s"', $suggestedBundleName), $e->getMessage()); - } - } - } - - public function getInvalidBundleNameTests() - { - return [ - 'Alternative will be found using levenshtein' => ['FoodBundle:Default:index', 'FooBundle:Default:index'], - 'Bundle does not exist at all' => ['CrazyBundle:Default:index', false], - ]; - } - - private function createParser() - { - $bundles = [ - 'SensioCmsFooBundle' => $this->getBundle('TestBundle\Sensio\Cms\FooBundle', 'SensioCmsFooBundle'), - 'FooBundle' => $this->getBundle('TestBundle\FooBundle', 'FooBundle'), - ]; - - $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock(); - $kernel - ->expects($this->any()) - ->method('getBundle') - ->willReturnCallback(function ($bundle) use ($bundles) { - if (!isset($bundles[$bundle])) { - throw new \InvalidArgumentException(sprintf('Invalid bundle name "%s"', $bundle)); - } - - return $bundles[$bundle]; - }) - ; - - $bundles = [ - 'SensioCmsFooBundle' => $this->getBundle('TestBundle\Sensio\Cms\FooBundle', 'SensioCmsFooBundle'), - 'FoooooBundle' => $this->getBundle('TestBundle\FooBundle', 'FoooooBundle'), - 'FooBundle' => $this->getBundle('TestBundle\FooBundle', 'FooBundle'), - ]; - $kernel - ->expects($this->any()) - ->method('getBundles') - ->willReturn($bundles) - ; - - return new ControllerNameParser($kernel); - } - - private function getBundle($namespace, $name) - { - $bundle = $this->getMockBuilder('Symfony\Component\HttpKernel\Bundle\BundleInterface')->getMock(); - $bundle->expects($this->any())->method('getName')->willReturn($name); - $bundle->expects($this->any())->method('getNamespace')->willReturn($namespace); - - return $bundle; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php index 3eea42c24ec45..b35c6d6cbd7b8 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerResolverTest.php @@ -14,7 +14,6 @@ use Psr\Container\ContainerInterface as Psr11ContainerInterface; use Psr\Log\LoggerInterface; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; -use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser; use Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver; use Symfony\Component\DependencyInjection\Container; use Symfony\Component\DependencyInjection\ContainerAwareInterface; @@ -49,31 +48,6 @@ public function testGetControllerOnContainerAwareInvokable() $this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $controller->getContainer()); } - /** - * @group legacy - * @expectedDeprecation Referencing controllers with FooBundle:Default:test is deprecated since Symfony 4.1. Use Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController::testAction instead. - */ - public function testGetControllerWithBundleNotation() - { - $shortName = 'FooBundle:Default:test'; - $parser = $this->createMockParser(); - $parser->expects($this->once()) - ->method('parse') - ->with($shortName) - ->willReturn('Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController::testAction') - ; - - $resolver = $this->createLegacyControllerResolver(null, null, $parser); - $request = Request::create('/'); - $request->attributes->set('_controller', $shortName); - - $controller = $resolver->getController($request); - - $this->assertInstanceOf('Symfony\Bundle\FrameworkBundle\Tests\Controller\ContainerAwareController', $controller[0]); - $this->assertInstanceOf('Symfony\Component\DependencyInjection\ContainerInterface', $controller[0]->getContainer()); - $this->assertSame('testAction', $controller[1]); - } - public function testContainerAwareControllerGetsContainerWhenNotSet() { class_exists(AbstractControllerTest::class); @@ -92,12 +66,11 @@ class_exists(AbstractControllerTest::class); $this->assertSame($container, $controller->getContainer()); } - /** - * @group legacy - * @expectedDeprecation Auto-injection of the container for "Symfony\Bundle\FrameworkBundle\Tests\Controller\TestAbstractController" is deprecated since Symfony 4.2. Configure it as a service instead. - */ public function testAbstractControllerGetsContainerWhenNotSet() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('"Symfony\\Bundle\\FrameworkBundle\\Tests\\Controller\\TestAbstractController" has no container set, did you forget to define it as a service subscriber?'); + class_exists(AbstractControllerTest::class); $controller = new TestAbstractController(false); @@ -105,7 +78,7 @@ class_exists(AbstractControllerTest::class); $container = new Container(); $container->set(TestAbstractController::class, $controller); - $resolver = $this->createLegacyControllerResolver(null, $container); + $resolver = $this->createControllerResolver(null, $container); $request = Request::create('/'); $request->attributes->set('_controller', TestAbstractController::class.'::fooAction'); @@ -114,12 +87,11 @@ class_exists(AbstractControllerTest::class); $this->assertSame($container, $controller->setContainer($container)); } - /** - * @group legacy - * @expectedDeprecation Auto-injection of the container for "Symfony\Bundle\FrameworkBundle\Tests\Controller\DummyController" is deprecated since Symfony 4.2. Configure it as a service instead. - */ - public function testAbstractControllerServiceWithFcqnIdGetsContainerWhenNotSet() + public function testAbstractControllerServiceWithFqcnIdGetsContainerWhenNotSet() { + $this->expectException('LogicException'); + $this->expectExceptionMessage('"Symfony\\Bundle\\FrameworkBundle\\Tests\\Controller\\DummyController" has no container set, did you forget to define it as a service subscriber?'); + class_exists(AbstractControllerTest::class); $controller = new DummyController(); @@ -127,7 +99,7 @@ class_exists(AbstractControllerTest::class); $container = new Container(); $container->set(DummyController::class, $controller); - $resolver = $this->createLegacyControllerResolver(null, $container); + $resolver = $this->createControllerResolver(null, $container); $request = Request::create('/'); $request->attributes->set('_controller', DummyController::class.'::fooAction'); @@ -176,19 +148,6 @@ class_exists(AbstractControllerTest::class); $this->assertSame($controllerContainer, $controller->getContainer()); } - protected function createLegacyControllerResolver(LoggerInterface $logger = null, Psr11ContainerInterface $container = null, ControllerNameParser $parser = null) - { - if (!$parser) { - $parser = $this->createMockParser(); - } - - if (!$container) { - $container = $this->createMockContainer(); - } - - return new ControllerResolver($container, $parser, $logger); - } - protected function createControllerResolver(LoggerInterface $logger = null, Psr11ContainerInterface $container = null) { if (!$container) { diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTraitTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTraitTest.php deleted file mode 100644 index 1d34089f2dc41..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/ControllerTraitTest.php +++ /dev/null @@ -1,545 +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\Tests\Controller; - -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; -use Symfony\Component\DependencyInjection\Container; -use Symfony\Component\Form\Form; -use Symfony\Component\Form\FormConfigInterface; -use Symfony\Component\HttpFoundation\BinaryFileResponse; -use Symfony\Component\HttpFoundation\File\File; -use Symfony\Component\HttpFoundation\JsonResponse; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpFoundation\ResponseHeaderBag; -use Symfony\Component\HttpFoundation\Session\Flash\FlashBag; -use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken; -use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken; -use Symfony\Component\Security\Core\User\User; -use Symfony\Component\Serializer\SerializerInterface; -use Symfony\Component\WebLink\Link; - -abstract class ControllerTraitTest extends TestCase -{ - abstract protected function createController(); - - public function testForward() - { - $request = Request::create('/'); - $request->setLocale('fr'); - $request->setRequestFormat('xml'); - - $requestStack = new RequestStack(); - $requestStack->push($request); - - $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(); - $kernel->expects($this->once())->method('handle')->willReturnCallback(function (Request $request) { - return new Response($request->getRequestFormat().'--'.$request->getLocale()); - }); - - $container = new Container(); - $container->set('request_stack', $requestStack); - $container->set('http_kernel', $kernel); - - $controller = $this->createController(); - $controller->setContainer($container); - - $response = $controller->forward('a_controller'); - $this->assertEquals('xml--fr', $response->getContent()); - } - - public function testGetUser() - { - $user = new User('user', 'pass'); - $token = new UsernamePasswordToken($user, 'pass', 'default', ['ROLE_USER']); - - $controller = $this->createController(); - $controller->setContainer($this->getContainerWithTokenStorage($token)); - - $this->assertSame($controller->getUser(), $user); - } - - public function testGetUserAnonymousUserConvertedToNull() - { - $token = new AnonymousToken('default', 'anon.'); - - $controller = $this->createController(); - $controller->setContainer($this->getContainerWithTokenStorage($token)); - - $this->assertNull($controller->getUser()); - } - - public function testGetUserWithEmptyTokenStorage() - { - $controller = $this->createController(); - $controller->setContainer($this->getContainerWithTokenStorage(null)); - - $this->assertNull($controller->getUser()); - } - - public function testGetUserWithEmptyContainer() - { - $this->expectException('LogicException'); - $this->expectExceptionMessage('The SecurityBundle is not registered in your application.'); - $controller = $this->createController(); - $controller->setContainer(new Container()); - - $controller->getUser(); - } - - private function getContainerWithTokenStorage($token = null): Container - { - $tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage')->getMock(); - $tokenStorage - ->expects($this->once()) - ->method('getToken') - ->willReturn($token); - - $container = new Container(); - $container->set('security.token_storage', $tokenStorage); - - return $container; - } - - public function testJson() - { - $controller = $this->createController(); - $controller->setContainer(new Container()); - - $response = $controller->json([]); - $this->assertInstanceOf(JsonResponse::class, $response); - $this->assertEquals('[]', $response->getContent()); - } - - public function testJsonWithSerializer() - { - $container = new Container(); - - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); - $serializer - ->expects($this->once()) - ->method('serialize') - ->with([], 'json', ['json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS]) - ->willReturn('[]'); - - $container->set('serializer', $serializer); - - $controller = $this->createController(); - $controller->setContainer($container); - - $response = $controller->json([]); - $this->assertInstanceOf(JsonResponse::class, $response); - $this->assertEquals('[]', $response->getContent()); - } - - public function testJsonWithSerializerContextOverride() - { - $container = new Container(); - - $serializer = $this->getMockBuilder(SerializerInterface::class)->getMock(); - $serializer - ->expects($this->once()) - ->method('serialize') - ->with([], 'json', ['json_encode_options' => 0, 'other' => 'context']) - ->willReturn('[]'); - - $container->set('serializer', $serializer); - - $controller = $this->createController(); - $controller->setContainer($container); - - $response = $controller->json([], 200, [], ['json_encode_options' => 0, 'other' => 'context']); - $this->assertInstanceOf(JsonResponse::class, $response); - $this->assertEquals('[]', $response->getContent()); - $response->setEncodingOptions(JSON_FORCE_OBJECT); - $this->assertEquals('{}', $response->getContent()); - } - - public function testFile() - { - $container = new Container(); - $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(); - $container->set('http_kernel', $kernel); - - $controller = $this->createController(); - $controller->setContainer($container); - - /* @var BinaryFileResponse $response */ - $response = $controller->file(new File(__FILE__)); - $this->assertInstanceOf(BinaryFileResponse::class, $response); - $this->assertSame(200, $response->getStatusCode()); - if ($response->headers->get('content-type')) { - $this->assertSame('text/x-php', $response->headers->get('content-type')); - } - $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); - $this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition')); - } - - public function testFileAsInline() - { - $controller = $this->createController(); - - /* @var BinaryFileResponse $response */ - $response = $controller->file(new File(__FILE__), null, ResponseHeaderBag::DISPOSITION_INLINE); - - $this->assertInstanceOf(BinaryFileResponse::class, $response); - $this->assertSame(200, $response->getStatusCode()); - if ($response->headers->get('content-type')) { - $this->assertSame('text/x-php', $response->headers->get('content-type')); - } - $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition')); - $this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition')); - } - - public function testFileWithOwnFileName() - { - $controller = $this->createController(); - - /* @var BinaryFileResponse $response */ - $fileName = 'test.php'; - $response = $controller->file(new File(__FILE__), $fileName); - - $this->assertInstanceOf(BinaryFileResponse::class, $response); - $this->assertSame(200, $response->getStatusCode()); - if ($response->headers->get('content-type')) { - $this->assertSame('text/x-php', $response->headers->get('content-type')); - } - $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); - $this->assertStringContainsString($fileName, $response->headers->get('content-disposition')); - } - - public function testFileWithOwnFileNameAsInline() - { - $controller = $this->createController(); - - /* @var BinaryFileResponse $response */ - $fileName = 'test.php'; - $response = $controller->file(new File(__FILE__), $fileName, ResponseHeaderBag::DISPOSITION_INLINE); - - $this->assertInstanceOf(BinaryFileResponse::class, $response); - $this->assertSame(200, $response->getStatusCode()); - if ($response->headers->get('content-type')) { - $this->assertSame('text/x-php', $response->headers->get('content-type')); - } - $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_INLINE, $response->headers->get('content-disposition')); - $this->assertStringContainsString($fileName, $response->headers->get('content-disposition')); - } - - public function testFileFromPath() - { - $controller = $this->createController(); - - /* @var BinaryFileResponse $response */ - $response = $controller->file(__FILE__); - - $this->assertInstanceOf(BinaryFileResponse::class, $response); - $this->assertSame(200, $response->getStatusCode()); - if ($response->headers->get('content-type')) { - $this->assertSame('text/x-php', $response->headers->get('content-type')); - } - $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); - $this->assertStringContainsString(basename(__FILE__), $response->headers->get('content-disposition')); - } - - public function testFileFromPathWithCustomizedFileName() - { - $controller = $this->createController(); - - /* @var BinaryFileResponse $response */ - $response = $controller->file(__FILE__, 'test.php'); - - $this->assertInstanceOf(BinaryFileResponse::class, $response); - $this->assertSame(200, $response->getStatusCode()); - if ($response->headers->get('content-type')) { - $this->assertSame('text/x-php', $response->headers->get('content-type')); - } - $this->assertStringContainsString(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $response->headers->get('content-disposition')); - $this->assertStringContainsString('test.php', $response->headers->get('content-disposition')); - } - - public function testFileWhichDoesNotExist() - { - $this->expectException('Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException'); - $controller = $this->createController(); - - $controller->file('some-file.txt', 'test.php'); - } - - public function testIsGranted() - { - $authorizationChecker = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface')->getMock(); - $authorizationChecker->expects($this->once())->method('isGranted')->willReturn(true); - - $container = new Container(); - $container->set('security.authorization_checker', $authorizationChecker); - - $controller = $this->createController(); - $controller->setContainer($container); - - $this->assertTrue($controller->isGranted('foo')); - } - - 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); - - $container = new Container(); - $container->set('security.authorization_checker', $authorizationChecker); - - $controller = $this->createController(); - $controller->setContainer($container); - - $controller->denyAccessUnlessGranted('foo'); - } - - public function testRenderViewTwig() - { - $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); - $twig->expects($this->once())->method('render')->willReturn('bar'); - - $container = new Container(); - $container->set('twig', $twig); - - $controller = $this->createController(); - $controller->setContainer($container); - - $this->assertEquals('bar', $controller->renderView('foo')); - } - - public function testRenderTwig() - { - $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); - $twig->expects($this->once())->method('render')->willReturn('bar'); - - $container = new Container(); - $container->set('twig', $twig); - - $controller = $this->createController(); - $controller->setContainer($container); - - $this->assertEquals('bar', $controller->render('foo')->getContent()); - } - - public function testStreamTwig() - { - $twig = $this->getMockBuilder('Twig\Environment')->disableOriginalConstructor()->getMock(); - - $container = new Container(); - $container->set('twig', $twig); - - $controller = $this->createController(); - $controller->setContainer($container); - - $this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $controller->stream('foo')); - } - - public function testRedirectToRoute() - { - $router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock(); - $router->expects($this->once())->method('generate')->willReturn('/foo'); - - $container = new Container(); - $container->set('router', $router); - - $controller = $this->createController(); - $controller->setContainer($container); - $response = $controller->redirectToRoute('foo'); - - $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); - $this->assertSame('/foo', $response->getTargetUrl()); - $this->assertSame(302, $response->getStatusCode()); - } - - /** - * @runInSeparateProcess - */ - public function testAddFlash() - { - $flashBag = new FlashBag(); - $session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Session')->getMock(); - $session->expects($this->once())->method('getFlashBag')->willReturn($flashBag); - - $container = new Container(); - $container->set('session', $session); - - $controller = $this->createController(); - $controller->setContainer($container); - $controller->addFlash('foo', 'bar'); - - $this->assertSame(['bar'], $flashBag->get('foo')); - } - - public function testCreateAccessDeniedException() - { - $controller = $this->createController(); - - $this->assertInstanceOf('Symfony\Component\Security\Core\Exception\AccessDeniedException', $controller->createAccessDeniedException()); - } - - public function testIsCsrfTokenValid() - { - $tokenManager = $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock(); - $tokenManager->expects($this->once())->method('isTokenValid')->willReturn(true); - - $container = new Container(); - $container->set('security.csrf.token_manager', $tokenManager); - - $controller = $this->createController(); - $controller->setContainer($container); - - $this->assertTrue($controller->isCsrfTokenValid('foo', 'bar')); - } - - public function testGenerateUrl() - { - $router = $this->getMockBuilder('Symfony\Component\Routing\RouterInterface')->getMock(); - $router->expects($this->once())->method('generate')->willReturn('/foo'); - - $container = new Container(); - $container->set('router', $router); - - $controller = $this->createController(); - $controller->setContainer($container); - - $this->assertEquals('/foo', $controller->generateUrl('foo')); - } - - public function testRedirect() - { - $controller = $this->createController(); - $response = $controller->redirect('https://dunglas.fr', 301); - - $this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response); - $this->assertSame('https://dunglas.fr', $response->getTargetUrl()); - $this->assertSame(301, $response->getStatusCode()); - } - - /** - * @group legacy - */ - public function testRenderViewTemplating() - { - $templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock(); - $templating->expects($this->once())->method('render')->willReturn('bar'); - - $container = new Container(); - $container->set('templating', $templating); - - $controller = $this->createController(); - $controller->setContainer($container); - - $this->assertEquals('bar', $controller->renderView('foo')); - } - - /** - * @group legacy - */ - public function testRenderTemplating() - { - $templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock(); - $templating->expects($this->once())->method('render')->willReturn('bar'); - - $container = new Container(); - $container->set('templating', $templating); - - $controller = $this->createController(); - $controller->setContainer($container); - - $this->assertEquals('bar', $controller->render('foo')->getContent()); - } - - /** - * @group legacy - */ - public function testStreamTemplating() - { - $templating = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock(); - - $container = new Container(); - $container->set('templating', $templating); - - $controller = $this->createController(); - $controller->setContainer($container); - - $this->assertInstanceOf('Symfony\Component\HttpFoundation\StreamedResponse', $controller->stream('foo')); - } - - public function testCreateNotFoundException() - { - $controller = $this->createController(); - - $this->assertInstanceOf('Symfony\Component\HttpKernel\Exception\NotFoundHttpException', $controller->createNotFoundException()); - } - - public function testCreateForm() - { - $form = new Form($this->getMockBuilder(FormConfigInterface::class)->getMock()); - - $formFactory = $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock(); - $formFactory->expects($this->once())->method('create')->willReturn($form); - - $container = new Container(); - $container->set('form.factory', $formFactory); - - $controller = $this->createController(); - $controller->setContainer($container); - - $this->assertEquals($form, $controller->createForm('foo')); - } - - public function testCreateFormBuilder() - { - $formBuilder = $this->getMockBuilder('Symfony\Component\Form\FormBuilderInterface')->getMock(); - - $formFactory = $this->getMockBuilder('Symfony\Component\Form\FormFactoryInterface')->getMock(); - $formFactory->expects($this->once())->method('createBuilder')->willReturn($formBuilder); - - $container = new Container(); - $container->set('form.factory', $formFactory); - - $controller = $this->createController(); - $controller->setContainer($container); - - $this->assertEquals($formBuilder, $controller->createFormBuilder('foo')); - } - - public function testGetDoctrine() - { - $doctrine = $this->getMockBuilder('Doctrine\Common\Persistence\ManagerRegistry')->getMock(); - - $container = new Container(); - $container->set('doctrine', $doctrine); - - $controller = $this->createController(); - $controller->setContainer($container); - - $this->assertEquals($doctrine, $controller->getDoctrine()); - } - - public function testAddLink() - { - $request = new Request(); - $link1 = new Link('mercure', 'https://demo.mercure.rocks'); - $link2 = new Link('self', 'https://example.com/foo'); - - $controller = $this->createController(); - $controller->addLink($request, $link1); - $controller->addLink($request, $link2); - - $links = $request->attributes->get('_links')->getLinks(); - $this->assertContains($link1, $links); - $this->assertContains($link2, $links); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php index 0eeb0293846dc..452c9ffd0d789 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TemplateControllerTest.php @@ -12,7 +12,6 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Controller\TemplateController; -use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface; use Symfony\Bundle\FrameworkBundle\Tests\TestCase; /** @@ -31,24 +30,10 @@ public function testTwig() $this->assertEquals('bar', $controller('mytemplate')->getContent()); } - /** - * @group legacy - */ - public function testTemplating() - { - $templating = $this->getMockBuilder(EngineInterface::class)->getMock(); - $templating->expects($this->exactly(2))->method('render')->willReturn('bar'); - - $controller = new TemplateController(null, $templating); - - $this->assertEquals('bar', $controller->templateAction('mytemplate')->getContent()); - $this->assertEquals('bar', $controller('mytemplate')->getContent()); - } - - public function testNoTwigNorTemplating() + public function testNoTwig() { $this->expectException('LogicException'); - $this->expectExceptionMessage('You can not use the TemplateController if the Templating Component or the Twig Bundle are not available.'); + $this->expectExceptionMessage('You can not use the TemplateController if the Twig Bundle is not available.'); $controller = new TemplateController(); $controller->templateAction('mytemplate')->getContent(); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TestAbstractController.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TestAbstractController.php new file mode 100644 index 0000000000000..30480d9f1d2d7 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TestAbstractController.php @@ -0,0 +1,58 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bundle\FrameworkBundle\Tests\Controller; + +use Psr\Container\ContainerInterface; +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; + +class TestAbstractController extends AbstractController +{ + private $throwOnUnexpectedService; + + public function __construct($throwOnUnexpectedService = true) + { + $this->throwOnUnexpectedService = $throwOnUnexpectedService; + } + + public function __call(string $method, array $arguments) + { + return $this->$method(...$arguments); + } + + public function setContainer(ContainerInterface $container): ?ContainerInterface + { + if (!$this->throwOnUnexpectedService) { + return parent::setContainer($container); + } + + $expected = self::getSubscribedServices(); + + foreach ($container->getServiceIds() as $id) { + if ('service_container' === $id) { + continue; + } + if (!isset($expected[$id])) { + throw new \UnexpectedValueException(sprintf('Service "%s" is not expected, as declared by %s::getSubscribedServices()', $id, AbstractController::class)); + } + $type = substr($expected[$id], 1); + if (!$container->get($id) instanceof $type) { + throw new \UnexpectedValueException(sprintf('Service "%s" is expected to be an instance of "%s", as declared by %s::getSubscribedServices()', $id, $type, AbstractController::class)); + } + } + + return parent::setContainer($container); + } + + public function fooAction() + { + } +} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TestController.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TestController.php deleted file mode 100644 index 58a49797caa0b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Controller/TestController.php +++ /dev/null @@ -1,32 +0,0 @@ -assertEquals('addExpressionLanguageProvider', $calls[0][0]); $this->assertEquals(new Reference('some_routing_provider'), $calls[0][1][0]); } - - /** - * @group legacy - * @expectedDeprecation Registering services tagged "security.expression_language_provider" with "Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddExpressionLanguageProvidersPass" is deprecated since Symfony 4.2, use the "Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddExpressionLanguageProvidersPass" instead. - */ - public function testProcessForSecurity() - { - $container = new ContainerBuilder(); - $container->addCompilerPass(new AddExpressionLanguageProvidersPass()); - - $definition = new Definition('\stdClass'); - $definition->addTag('security.expression_language_provider'); - $container->setDefinition('some_security_provider', $definition->setPublic(true)); - - $container->register('security.expression_language', '\stdClass')->setPublic(true); - $container->compile(); - - $calls = $container->getDefinition('security.expression_language')->getMethodCalls(); - $this->assertCount(1, $calls); - $this->assertEquals('registerProvider', $calls[0][0]); - $this->assertEquals(new Reference('some_security_provider'), $calls[0][1][0]); - } - - /** - * @group legacy - * @expectedDeprecation Registering services tagged "security.expression_language_provider" with "Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\AddExpressionLanguageProvidersPass" is deprecated since Symfony 4.2, use the "Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\AddExpressionLanguageProvidersPass" instead. - */ - public function testProcessForSecurityAlias() - { - $container = new ContainerBuilder(); - $container->addCompilerPass(new AddExpressionLanguageProvidersPass()); - - $definition = new Definition('\stdClass'); - $definition->addTag('security.expression_language_provider'); - $container->setDefinition('some_security_provider', $definition->setPublic(true)); - - $container->register('my_security.expression_language', '\stdClass')->setPublic(true); - $container->setAlias('security.expression_language', 'my_security.expression_language'); - $container->compile(); - - $calls = $container->getDefinition('my_security.expression_language')->getMethodCalls(); - $this->assertCount(1, $calls); - $this->assertEquals('registerProvider', $calls[0][0]); - $this->assertEquals(new Reference('some_security_provider'), $calls[0][1][0]); - } - - /** - * @group legacy - */ - public function testProcessIgnoreSecurity() - { - $container = new ContainerBuilder(); - $container->addCompilerPass(new AddExpressionLanguageProvidersPass(false)); - - $definition = new Definition('\stdClass'); - $definition->addTag('security.expression_language_provider'); - $container->setDefinition('some_security_provider', $definition->setPublic(true)); - - $container->register('security.expression_language', '\stdClass')->setPublic(true); - $container->compile(); - - $calls = $container->getDefinition('security.expression_language')->getMethodCalls(); - $this->assertCount(0, $calls); - } - - /** - * @group legacy - */ - public function testProcessIgnoreSecurityAlias() - { - $container = new ContainerBuilder(); - $container->addCompilerPass(new AddExpressionLanguageProvidersPass(false)); - - $definition = new Definition('\stdClass'); - $definition->addTag('security.expression_language_provider'); - $container->setDefinition('some_security_provider', $definition->setPublic(true)); - - $container->register('my_security.expression_language', '\stdClass')->setPublic(true); - $container->setAlias('security.expression_language', 'my_security.expression_language'); - $container->compile(); - - $calls = $container->getDefinition('my_security.expression_language')->getMethodCalls(); - $this->assertCount(0, $calls); - } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CacheCollectorPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CacheCollectorPassTest.php deleted file mode 100644 index d7613d5ae5d0a..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CacheCollectorPassTest.php +++ /dev/null @@ -1,52 +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\Tests\DependencyInjection\Compiler; - -use PHPUnit\Framework\TestCase; -use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CacheCollectorPass; -use Symfony\Component\Cache\Adapter\FilesystemAdapter; -use Symfony\Component\Cache\Adapter\TagAwareAdapter; -use Symfony\Component\Cache\Adapter\TraceableAdapter; -use Symfony\Component\Cache\Adapter\TraceableTagAwareAdapter; -use Symfony\Component\Cache\DataCollector\CacheDataCollector; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Reference; - -/** - * @group legacy - */ -class CacheCollectorPassTest extends TestCase -{ - public function testProcess() - { - $container = new ContainerBuilder(); - $container - ->register('fs', FilesystemAdapter::class) - ->addTag('cache.pool'); - $container - ->register('tagged_fs', TagAwareAdapter::class) - ->addArgument(new Reference('fs')) - ->addTag('cache.pool'); - - $collector = $container->register('data_collector.cache', CacheDataCollector::class); - (new CacheCollectorPass())->process($container); - - $this->assertEquals([ - ['addInstance', ['fs', new Reference('fs')]], - ['addInstance', ['tagged_fs', new Reference('tagged_fs')]], - ], $collector->getMethodCalls()); - - $this->assertSame(TraceableAdapter::class, $container->findDefinition('fs')->getClass()); - $this->assertSame(TraceableTagAwareAdapter::class, $container->getDefinition('tagged_fs')->getClass()); - $this->assertFalse($collector->isPublic(), 'The "data_collector.cache" should be private after processing'); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolClearerPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolClearerPassTest.php deleted file mode 100644 index 494cf6f0941b2..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolClearerPassTest.php +++ /dev/null @@ -1,76 +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\Tests\DependencyInjection\Compiler; - -use PHPUnit\Framework\TestCase; -use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CachePoolClearerPass; -use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CachePoolPass; -use Symfony\Component\DependencyInjection\Compiler\RemoveUnusedDefinitionsPass; -use Symfony\Component\DependencyInjection\Compiler\RepeatedPass; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Definition; -use Symfony\Component\DependencyInjection\Reference; -use Symfony\Component\HttpKernel\CacheClearer\Psr6CacheClearer; - -/** - * @group legacy - */ -class CachePoolClearerPassTest extends TestCase -{ - public function testPoolRefsAreWeak() - { - $container = new ContainerBuilder(); - $container->setParameter('kernel.container_class', 'app'); - $container->setParameter('kernel.project_dir', 'foo'); - - $globalClearer = new Definition(Psr6CacheClearer::class); - $container->setDefinition('cache.global_clearer', $globalClearer); - - $publicPool = new Definition(); - $publicPool->addArgument('namespace'); - $publicPool->addTag('cache.pool', ['clearer' => 'clearer_alias']); - $container->setDefinition('public.pool', $publicPool); - - $publicPool = new Definition(); - $publicPool->addArgument('namespace'); - $publicPool->addTag('cache.pool', ['clearer' => 'clearer_alias', 'name' => 'pool2']); - $container->setDefinition('public.pool2', $publicPool); - - $privatePool = new Definition(); - $privatePool->setPublic(false); - $privatePool->addArgument('namespace'); - $privatePool->addTag('cache.pool', ['clearer' => 'clearer_alias']); - $container->setDefinition('private.pool', $privatePool); - - $clearer = new Definition(); - $container->setDefinition('clearer', $clearer); - $container->setAlias('clearer_alias', 'clearer'); - - $pass = new RemoveUnusedDefinitionsPass(); - foreach ($container->getCompiler()->getPassConfig()->getRemovingPasses() as $removingPass) { - if ($removingPass instanceof RepeatedPass) { - $pass->setRepeatedPass(new RepeatedPass([$pass])); - break; - } - } - foreach ([new CachePoolPass(), $pass, new CachePoolClearerPass()] as $pass) { - $pass->process($container); - } - - $expected = [[ - 'public.pool' => new Reference('public.pool'), - 'pool2' => new Reference('public.pool2'), - ]]; - $this->assertEquals($expected, $clearer->getArguments()); - $this->assertEquals($expected, $globalClearer->getArguments()); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPassTest.php deleted file mode 100644 index 6bc90a478fd56..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPassTest.php +++ /dev/null @@ -1,131 +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\Tests\DependencyInjection\Compiler; - -use PHPUnit\Framework\TestCase; -use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CachePoolPass; -use Symfony\Component\Cache\Adapter\ArrayAdapter; -use Symfony\Component\DependencyInjection\ChildDefinition; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Definition; -use Symfony\Component\DependencyInjection\Reference; - -/** - * @group legacy - */ -class CachePoolPassTest extends TestCase -{ - private $cachePoolPass; - - protected function setUp(): void - { - $this->cachePoolPass = new CachePoolPass(); - } - - public function testNamespaceArgumentIsReplaced() - { - $container = new ContainerBuilder(); - $container->setParameter('kernel.container_class', 'app'); - $container->setParameter('kernel.project_dir', 'foo'); - $adapter = new Definition(); - $adapter->setAbstract(true); - $adapter->addTag('cache.pool'); - $container->setDefinition('app.cache_adapter', $adapter); - $container->setAlias('app.cache_adapter_alias', 'app.cache_adapter'); - $cachePool = new ChildDefinition('app.cache_adapter_alias'); - $cachePool->addArgument(null); - $cachePool->addTag('cache.pool'); - $container->setDefinition('app.cache_pool', $cachePool); - - $this->cachePoolPass->process($container); - - $this->assertSame('z3X945Jbf5', $cachePool->getArgument(0)); - } - - public function testNamespaceArgumentIsNotReplacedIfArrayAdapterIsUsed() - { - $container = new ContainerBuilder(); - $container->setParameter('kernel.container_class', 'app'); - $container->setParameter('kernel.project_dir', 'foo'); - - $container->register('cache.adapter.array', ArrayAdapter::class)->addArgument(0); - - $cachePool = new ChildDefinition('cache.adapter.array'); - $cachePool->addTag('cache.pool'); - $container->setDefinition('app.cache_pool', $cachePool); - - $this->cachePoolPass->process($container); - - $this->assertCount(0, $container->getDefinition('app.cache_pool')->getArguments()); - } - - public function testArgsAreReplaced() - { - $container = new ContainerBuilder(); - $container->setParameter('kernel.container_class', 'app'); - $container->setParameter('cache.prefix.seed', 'foo'); - $cachePool = new Definition(); - $cachePool->addTag('cache.pool', [ - 'provider' => 'foobar', - 'default_lifetime' => 3, - ]); - $cachePool->addArgument(null); - $cachePool->addArgument(null); - $cachePool->addArgument(null); - $container->setDefinition('app.cache_pool', $cachePool); - - $this->cachePoolPass->process($container); - - $this->assertInstanceOf(Reference::class, $cachePool->getArgument(0)); - $this->assertSame('foobar', (string) $cachePool->getArgument(0)); - $this->assertSame('tQNhcV-8xa', $cachePool->getArgument(1)); - $this->assertSame(3, $cachePool->getArgument(2)); - } - - public function testWithNameAttribute() - { - $container = new ContainerBuilder(); - $container->setParameter('kernel.container_class', 'app'); - $container->setParameter('cache.prefix.seed', 'foo'); - $cachePool = new Definition(); - $cachePool->addTag('cache.pool', [ - 'name' => 'foobar', - 'provider' => 'foobar', - ]); - $cachePool->addArgument(null); - $cachePool->addArgument(null); - $cachePool->addArgument(null); - $container->setDefinition('app.cache_pool', $cachePool); - - $this->cachePoolPass->process($container); - - $this->assertSame('+naTpPa4Sm', $cachePool->getArgument(1)); - } - - 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.container_class', 'app'); - $container->setParameter('kernel.project_dir', 'foo'); - $adapter = new Definition(); - $adapter->setAbstract(true); - $adapter->addTag('cache.pool'); - $container->setDefinition('app.cache_adapter', $adapter); - $cachePool = new ChildDefinition('app.cache_adapter'); - $cachePool->addTag('cache.pool', ['foobar' => 123]); - $container->setDefinition('app.cache_pool', $cachePool); - - $this->cachePoolPass->process($container); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPrunerPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPrunerPassTest.php deleted file mode 100644 index b47dc907c3c88..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/CachePoolPrunerPassTest.php +++ /dev/null @@ -1,73 +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\Tests\DependencyInjection\Compiler; - -use PHPUnit\Framework\TestCase; -use Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\CachePoolPrunerPass; -use Symfony\Component\Cache\Adapter\FilesystemAdapter; -use Symfony\Component\Cache\Adapter\PhpFilesAdapter; -use Symfony\Component\DependencyInjection\Argument\IteratorArgument; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Reference; - -/** - * @group legacy - */ -class CachePoolPrunerPassTest extends TestCase -{ - public function testCompilerPassReplacesCommandArgument() - { - $container = new ContainerBuilder(); - $container->register('console.command.cache_pool_prune')->addArgument([]); - $container->register('pool.foo', FilesystemAdapter::class)->addTag('cache.pool'); - $container->register('pool.bar', PhpFilesAdapter::class)->addTag('cache.pool'); - - $pass = new CachePoolPrunerPass(); - $pass->process($container); - - $expected = [ - 'pool.foo' => new Reference('pool.foo'), - 'pool.bar' => new Reference('pool.bar'), - ]; - $argument = $container->getDefinition('console.command.cache_pool_prune')->getArgument(0); - - $this->assertInstanceOf(IteratorArgument::class, $argument); - $this->assertEquals($expected, $argument->getValues()); - } - - public function testCompilePassIsIgnoredIfCommandDoesNotExist() - { - $container = new ContainerBuilder(); - - $definitionsBefore = \count($container->getDefinitions()); - $aliasesBefore = \count($container->getAliases()); - - $pass = new CachePoolPrunerPass(); - $pass->process($container); - - // the container is untouched (i.e. no new definitions or aliases) - $this->assertCount($definitionsBefore, $container->getDefinitions()); - $this->assertCount($aliasesBefore, $container->getAliases()); - } - - 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'); - - $pass = new CachePoolPrunerPass(); - $pass->process($container); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/DataCollectorTranslatorPassTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/DataCollectorTranslatorPassTest.php index 138a0e4bbc27a..9166fab5b230d 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/DataCollectorTranslatorPassTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Compiler/DataCollectorTranslatorPassTest.php @@ -108,7 +108,7 @@ public function getNotImplementingTranslatorBagInterfaceTranslatorClassNames() class TranslatorWithTranslatorBag implements TranslatorInterface { - public function trans($id, array $parameters = [], $domain = null, $locale = null): string + public function trans(string $id, array $parameters = [], string $domain = null, string $locale = null): string { } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php index a95e649c80c91..9c3ab3cd8aa56 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/ConfigurationTest.php @@ -21,6 +21,7 @@ use Symfony\Component\Lock\Store\SemaphoreStore; use Symfony\Component\Mailer\Mailer; use Symfony\Component\Messenger\MessageBusInterface; +use Symfony\Component\Notifier\Notifier; class ConfigurationTest extends TestCase { @@ -35,22 +36,6 @@ public function testDefaultConfig() ); } - /** - * @group legacy - */ - public function testDoNoDuplicateDefaultFormResources() - { - $input = ['templating' => [ - 'form' => ['resources' => ['FrameworkBundle:Form']], - 'engines' => ['php'], - ]]; - - $processor = new Processor(); - $config = $processor->processConfiguration(new Configuration(true), [$input]); - - $this->assertEquals(['FrameworkBundle:Form'], $config['templating']['form']['resources']); - } - public function getTestValidSessionName() { return [ @@ -422,15 +407,6 @@ protected static function getBundleDefaultConfig() 'enabled' => false, 'formats' => [], ], - 'templating' => [ - 'enabled' => false, - 'hinclude_default_template' => null, - 'form' => [ - 'resources' => ['FrameworkBundle:Form'], - ], - 'engines' => [], - 'loaders' => [], - ], 'assets' => [ 'enabled' => !class_exists(FullStack::class), 'version_strategy' => null, @@ -494,6 +470,14 @@ class_exists(SemaphoreStore::class) && SemaphoreStore::isSupported() ? 'semaphor 'transports' => [], 'enabled' => !class_exists(FullStack::class) && class_exists(Mailer::class), ], + 'notifier' => [ + 'enabled' => !class_exists(FullStack::class) && class_exists(Notifier::class), + 'chatter_transports' => [], + 'texter_transports' => [], + 'channel_policy' => [], + 'admin_recipients' => [], + 'notification_on_failed_messages' => false, + ], 'error_controller' => 'error_controller', 'secrets' => [ 'enabled' => true, diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/Resources/translations/test_default.en.xlf b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/Resources/translations/test_default.en.xlf deleted file mode 100644 index e69de29bb2d1d..0000000000000 diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/template_and_fragments.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/template_and_fragments.php deleted file mode 100644 index 6fd941d9f46c0..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/template_and_fragments.php +++ /dev/null @@ -1,18 +0,0 @@ -loadFromExtension('framework', [ - 'templating' => [ - 'cache' => '/path/to/cache', - 'engines' => ['php', 'twig'], - 'loader' => ['loader.foo', 'loader.bar'], - 'form' => [ - 'resources' => ['theme1', 'theme2'], - ], - 'hinclude_default_template' => 'global_hinclude_template', - ], - 'assets' => null, - 'fragments' => [ - 'enabled' => true, - 'hinclude_default_template' => 'global_hinclude_template', - ], -]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/templating.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/templating.php deleted file mode 100644 index a7edabf763afd..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/templating.php +++ /dev/null @@ -1,14 +0,0 @@ -loadFromExtension('framework', [ - 'templating' => [ - 'cache' => '/path/to/cache', - 'engines' => ['php', 'twig'], - 'loader' => ['loader.foo', 'loader.bar'], - 'form' => [ - 'resources' => ['theme1', 'theme2'], - ], - 'hinclude_default_template' => 'global_hinclude_template', - ], - 'assets' => null, -]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/templating_disabled.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/templating_disabled.php deleted file mode 100644 index 2d5e6d779f79c..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/templating_disabled.php +++ /dev/null @@ -1,5 +0,0 @@ -loadFromExtension('framework', [ - 'templating' => false, -]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/templating_no_assets.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/templating_no_assets.php deleted file mode 100644 index f4d5a28aafc67..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/templating_no_assets.php +++ /dev/null @@ -1,7 +0,0 @@ -loadFromExtension('framework', [ - 'templating' => [ - 'engines' => ['php', 'twig'], - ], -]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/templating_php_assets_disabled.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/templating_php_assets_disabled.php deleted file mode 100644 index 851a7e140c747..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/templating_php_assets_disabled.php +++ /dev/null @@ -1,8 +0,0 @@ -loadFromExtension('framework', [ - 'assets' => false, - 'templating' => [ - 'engines' => ['php'], - ], -]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/validation_strict_email_and_validation_mode.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/validation_strict_email_and_validation_mode.php deleted file mode 100644 index 414b323efedef..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/validation_strict_email_and_validation_mode.php +++ /dev/null @@ -1,8 +0,0 @@ -loadFromExtension('framework', [ - 'validation' => [ - 'strict_email' => true, - 'email_validation_mode' => 'strict', - ], -]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/validation_strict_email_disabled.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/validation_strict_email_disabled.php deleted file mode 100644 index b5a8b7bba698b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/validation_strict_email_disabled.php +++ /dev/null @@ -1,7 +0,0 @@ -loadFromExtension('framework', [ - 'validation' => [ - 'strict_email' => false, - ], -]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/validation_strict_email_enabled.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/validation_strict_email_enabled.php deleted file mode 100644 index caa47d74700f6..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/validation_strict_email_enabled.php +++ /dev/null @@ -1,7 +0,0 @@ -loadFromExtension('framework', [ - 'validation' => [ - 'strict_email' => true, - ], -]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflow-legacy.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflow-legacy.php deleted file mode 100644 index cad94fc773b87..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflow-legacy.php +++ /dev/null @@ -1,29 +0,0 @@ -loadFromExtension('framework', [ - 'workflows' => [ - 'legacy' => [ - 'type' => 'state_machine', - 'marking_store' => [ - 'type' => 'single_state', - 'arguments' => [ - 'state', - ], - ], - 'supports' => [ - stdClass::class, - ], - 'initial_place' => 'draft', - 'places' => [ - 'draft', - 'published', - ], - 'transitions' => [ - 'publish' => [ - 'from' => 'draft', - 'to' => 'published', - ], - ], - ], - ], -]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflow_legacy_with_arguments_and_service.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflow_legacy_with_arguments_and_service.php deleted file mode 100644 index 003b99f210973..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflow_legacy_with_arguments_and_service.php +++ /dev/null @@ -1,31 +0,0 @@ -loadFromExtension('framework', [ - 'workflows' => [ - 'my_workflow' => [ - 'marking_store' => [ - 'arguments' => ['a', 'b'], - 'service' => 'workflow_service', - ], - 'supports' => [ - FrameworkExtensionTest::class, - ], - 'places' => [ - 'first', - 'last', - ], - 'transitions' => [ - 'go' => [ - 'from' => [ - 'first', - ], - 'to' => [ - 'last', - ], - ], - ], - ], - ], -]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflow_legacy_with_type_and_service.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflow_legacy_with_type_and_service.php deleted file mode 100644 index 15189349bd83d..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflow_legacy_with_type_and_service.php +++ /dev/null @@ -1,31 +0,0 @@ -loadFromExtension('framework', [ - 'workflows' => [ - 'my_workflow' => [ - 'marking_store' => [ - 'type' => 'method', - 'service' => 'workflow_service', - ], - 'supports' => [ - FrameworkExtensionTest::class, - ], - 'places' => [ - 'first', - 'last', - ], - 'transitions' => [ - 'go' => [ - 'from' => [ - 'first', - ], - 'to' => [ - 'last', - ], - ], - ], - ], - ], -]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflows_explicitly_enabled.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflows_explicitly_enabled.php index e6f261f8f2f7a..f048de1ceb5ad 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflows_explicitly_enabled.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflows_explicitly_enabled.php @@ -10,8 +10,8 @@ 'places' => ['bar', 'baz'], 'transitions' => [ 'bar_baz' => [ - 'from' => ['foo'], - 'to' => ['bar'], + 'from' => ['bar'], + 'to' => ['baz'], ], ], ], diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflows_explicitly_enabled_named_workflows.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflows_explicitly_enabled_named_workflows.php index e4bc05a66f46f..f79a2d10e97f9 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflows_explicitly_enabled_named_workflows.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/php/workflows_explicitly_enabled_named_workflows.php @@ -10,8 +10,8 @@ 'places' => ['bar', 'baz'], 'transitions' => [ 'bar_baz' => [ - 'from' => ['foo'], - 'to' => ['bar'], + 'from' => ['bar'], + 'to' => ['baz'], ], ], ], diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/template_and_fragments.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/template_and_fragments.xml deleted file mode 100644 index d253e9f5deeed..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/template_and_fragments.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - loader.foo - loader.bar - php - twig - - theme1 - theme2 - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating.xml deleted file mode 100644 index 192533dbf617a..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - loader.foo - loader.bar - php - twig - - theme1 - theme2 - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating_disabled.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating_disabled.xml deleted file mode 100644 index 8fda04d92a591..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating_disabled.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating_no_assets.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating_no_assets.xml deleted file mode 100644 index 7bba936c5a58e..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating_no_assets.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - php - twig - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating_php_translator_disabled.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating_php_translator_disabled.xml deleted file mode 100644 index 8e0a8cc039cb5..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating_php_translator_disabled.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - php - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating_php_translator_enabled.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating_php_translator_enabled.xml deleted file mode 100644 index d1cb1fad83367..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/templating_php_translator_enabled.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - php - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_strict_email_and_validation_mode.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_strict_email_and_validation_mode.xml deleted file mode 100644 index a88a37f26b03e..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_strict_email_and_validation_mode.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_strict_email_disabled.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_strict_email_disabled.xml deleted file mode 100644 index fa41396161130..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_strict_email_disabled.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_strict_email_enabled.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_strict_email_enabled.xml deleted file mode 100644 index ec5c6b94e6592..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/validation_strict_email_enabled.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflow-legacy.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflow-legacy.xml deleted file mode 100644 index 5a46d24d0df08..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflow-legacy.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - state - - stdClass - - - - draft - published - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflow_legacy_with_arguments_and_service.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflow_legacy_with_arguments_and_service.xml deleted file mode 100644 index cdb2f997357ee..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflow_legacy_with_arguments_and_service.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - a - a - - Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\FrameworkExtensionTest - - - - a - a - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflow_legacy_with_type_and_service.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflow_legacy_with_type_and_service.xml deleted file mode 100644 index e137f9b4b041b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflow_legacy_with_type_and_service.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\FrameworkExtensionTest - - - - a - a - - - - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflows_explicitly_enabled.xml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflows_explicitly_enabled.xml index bb544d8979bb2..af93d44e18387 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflows_explicitly_enabled.xml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/xml/workflows_explicitly_enabled.xml @@ -6,7 +6,7 @@ http://symfony.com/schema/dic/symfony https://symfony.com/schema/dic/symfony/symfony-1.0.xsd"> - + Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\FrameworkExtensionTest bar baz diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/template_and_fragments.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/template_and_fragments.yml deleted file mode 100644 index dbf7b697541e0..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/template_and_fragments.yml +++ /dev/null @@ -1,12 +0,0 @@ -framework: - fragments: - enabled: true - hinclude_default_template: global_hinclude_template - templating: - engines: [php, twig] - loader: [loader.foo, loader.bar] - cache: /path/to/cache - form: - resources: [theme1, theme2] - hinclude_default_template: global_hinclude_template - assets: ~ diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating.yml deleted file mode 100644 index d307e1609b090..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating.yml +++ /dev/null @@ -1,9 +0,0 @@ -framework: - templating: - engines: [php, twig] - loader: [loader.foo, loader.bar] - cache: /path/to/cache - form: - resources: [theme1, theme2] - hinclude_default_template: global_hinclude_template - assets: ~ diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_disabled.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_disabled.yml deleted file mode 100644 index 1e548b859473c..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_disabled.yml +++ /dev/null @@ -1,2 +0,0 @@ -framework: - templating: false diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_no_assets.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_no_assets.yml deleted file mode 100644 index 393477aeb49ac..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_no_assets.yml +++ /dev/null @@ -1,3 +0,0 @@ -framework: - templating: - engines: [php, twig] diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_php_assets_disabled.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_php_assets_disabled.yml deleted file mode 100644 index 7ef6b3e57c292..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_php_assets_disabled.yml +++ /dev/null @@ -1,4 +0,0 @@ -framework: - assets: false - templating: - engines: [php] diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_php_translator_disabled.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_php_translator_disabled.yml deleted file mode 100644 index fe0f3e83b5683..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_php_translator_disabled.yml +++ /dev/null @@ -1,4 +0,0 @@ -framework: - translator: false - templating: - engines: [php] diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_php_translator_enabled.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_php_translator_enabled.yml deleted file mode 100644 index 0991a2007d77f..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/templating_php_translator_enabled.yml +++ /dev/null @@ -1,4 +0,0 @@ -framework: - translator: true - templating: - engines: [php] diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/validation_strict_email_and_validation_mode.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/validation_strict_email_and_validation_mode.yml deleted file mode 100644 index 64e658ba69436..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/validation_strict_email_and_validation_mode.yml +++ /dev/null @@ -1,4 +0,0 @@ -framework: - validation: - strict_email: true - email_validation_mode: html5 diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/validation_strict_email_disabled.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/validation_strict_email_disabled.yml deleted file mode 100644 index b5be5f598b14c..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/validation_strict_email_disabled.yml +++ /dev/null @@ -1,3 +0,0 @@ -framework: - validation: - strict_email: false diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/validation_strict_email_enabled.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/validation_strict_email_enabled.yml deleted file mode 100644 index 1c805f9b923d2..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/validation_strict_email_enabled.yml +++ /dev/null @@ -1,3 +0,0 @@ -framework: - validation: - strict_email: true diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflow-legacy.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflow-legacy.yml deleted file mode 100644 index 19f51dc9f4119..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflow-legacy.yml +++ /dev/null @@ -1,18 +0,0 @@ -framework: - workflows: - legacy: - type: state_machine - marking_store: - type: single_state - arguments: - - state - initial_place: draft - supports: - - stdClass - places: - - draft - - published - transitions: - publish: - from: draft - to: published diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflow_legacy_with_arguments_and_service.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflow_legacy_with_arguments_and_service.yml deleted file mode 100644 index a46d4b67e6b24..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflow_legacy_with_arguments_and_service.yml +++ /dev/null @@ -1,19 +0,0 @@ -framework: - workflows: - my_workflow: - marking_store: - arguments: - - a - - b - service: workflow_service - supports: - - Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\FrameworkExtensionTest - places: - - first - - last - transitions: - go: - from: - - first - to: - - last diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflow_legacy_with_type_and_service.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflow_legacy_with_type_and_service.yml deleted file mode 100644 index 33ee68b1bc810..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflow_legacy_with_type_and_service.yml +++ /dev/null @@ -1,17 +0,0 @@ -framework: - workflows: - my_workflow: - marking_store: - type: method - service: workflow_service - supports: - - Symfony\Bundle\FrameworkBundle\Tests\DependencyInjection\FrameworkExtensionTest - places: - - first - - last - transitions: - go: - from: - - first - to: - - last diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflows_explicitly_enabled.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflows_explicitly_enabled.yml index bee231736b233..bbecf4bfc420e 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflows_explicitly_enabled.yml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflows_explicitly_enabled.yml @@ -12,5 +12,5 @@ framework: - baz transitions: bar_baz: - from: [foo] + from: [bar] to: [bar] diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflows_explicitly_enabled_named_workflows.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflows_explicitly_enabled_named_workflows.yml index c0462c9ab8c9d..786e3bcad292e 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflows_explicitly_enabled_named_workflows.yml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/Fixtures/yml/workflows_explicitly_enabled_named_workflows.yml @@ -11,5 +11,5 @@ framework: - baz transitions: bar_baz: - from: [foo] - to: [bar] + from: [bar] + to: [baz] diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php index 8366faf918b5b..0f90116ca10a0 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/FrameworkExtensionTest.php @@ -53,9 +53,7 @@ use Symfony\Component\Translation\DependencyInjection\TranslatorPass; use Symfony\Component\Validator\DependencyInjection\AddConstraintValidatorsPass; use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader; -use Symfony\Component\Validator\Util\LegacyTranslatorProxy; use Symfony\Component\Workflow; -use Symfony\Contracts\Translation\TranslatorInterface; abstract class FrameworkExtensionTest extends TestCase { @@ -161,15 +159,6 @@ public function testEsiDisabled() $this->assertFalse($container->hasDefinition('esi')); } - /** - * @group legacy - */ - public function testAmbiguousWhenBothTemplatingAndFragments() - { - $this->expectException('LogicException'); - $this->createContainerFromFile('template_and_fragments'); - } - public function testSsi() { $container = $this->createContainerFromFile('full'); @@ -288,33 +277,6 @@ public function testWorkflows() $this->assertGreaterThan(0, \count($registryDefinition->getMethodCalls())); } - /** - * @group legacy - */ - public function testWorkflowLegacy() - { - $container = $this->createContainerFromFile('workflow-legacy'); - - $this->assertTrue($container->hasDefinition('state_machine.legacy'), 'Workflow is registered as a service'); - $this->assertSame('state_machine.abstract', $container->getDefinition('state_machine.legacy')->getParent()); - $this->assertTrue($container->hasDefinition('state_machine.legacy.definition'), 'Workflow definition is registered as a service'); - - $workflowDefinition = $container->getDefinition('state_machine.legacy.definition'); - - $this->assertSame(['draft'], $workflowDefinition->getArgument(2)); - - $this->assertSame( - [ - 'draft', - 'published', - ], - $workflowDefinition->getArgument(0), - 'Places are passed to the workflow definition' - ); - - $this->assertSame(['workflow.definition' => [['name' => 'legacy', 'type' => 'state_machine']]], $workflowDefinition->getTags()); - } - public function testWorkflowAreValidated() { $this->expectException('Symfony\Component\Workflow\Exception\InvalidDefinitionException'); @@ -322,13 +284,6 @@ public function testWorkflowAreValidated() $this->createContainerFromFile('workflow_not_valid'); } - public function testWorkflowCannotHaveBothTypeAndService() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $this->expectExceptionMessage('"type" and "service" cannot be used together.'); - $this->createContainerFromFile('workflow_legacy_with_type_and_service'); - } - public function testWorkflowCannotHaveBothSupportsAndSupportStrategy() { $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); @@ -343,16 +298,6 @@ public function testWorkflowShouldHaveOneOfSupportsAndSupportStrategy() $this->createContainerFromFile('workflow_without_support_and_support_strategy'); } - /** - * @group legacy - */ - public function testWorkflowCannotHaveBothArgumentsAndService() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $this->expectExceptionMessage('"arguments" and "service" cannot be used together.'); - $this->createContainerFromFile('workflow_legacy_with_arguments_and_service'); - } - public function testWorkflowMultipleTransitionsWithSameName() { $container = $this->createContainerFromFile('workflow_with_multiple_transitions_with_same_name'); @@ -454,14 +399,14 @@ public function testWorkflowServicesCanBeEnabled() $this->assertTrue($container->hasDefinition('console.command.workflow_dump')); } - public function testExplicitlyEnabledWorkflows() + public function testWorkflowsExplicitlyEnabled() { $container = $this->createContainerFromFile('workflows_explicitly_enabled'); $this->assertTrue($container->hasDefinition('workflow.foo.definition')); } - public function testExplicitlyEnabledWorkflowNamedWorkflows() + public function testWorkflowsNamedExplicitlyEnabled() { $container = $this->createContainerFromFile('workflows_explicitly_enabled_named_workflows'); @@ -570,40 +515,6 @@ public function testEmptyRequestFormats() $this->assertFalse($container->hasDefinition('request.add_request_formats_listener'), '->registerRequestConfiguration() does not load request.xml when no request formats are defined'); } - /** - * @group legacy - */ - public function testTemplating() - { - $container = $this->createContainerFromFile('templating'); - - $this->assertTrue($container->hasDefinition('templating.name_parser'), '->registerTemplatingConfiguration() loads templating.xml'); - - $this->assertEquals('templating.engine.delegating', (string) $container->getAlias('templating'), '->registerTemplatingConfiguration() configures delegating loader if multiple engines are provided'); - - $this->assertEquals($container->getDefinition('templating.loader.chain'), $container->getDefinition('templating.loader.wrapped'), '->registerTemplatingConfiguration() configures loader chain if multiple loaders are provided'); - - $this->assertEquals($container->getDefinition('templating.loader'), $container->getDefinition('templating.loader.cache'), '->registerTemplatingConfiguration() configures the loader to use cache'); - - $this->assertEquals('%templating.loader.cache.path%', $container->getDefinition('templating.loader.cache')->getArgument(1)); - $this->assertEquals('/path/to/cache', $container->getParameter('templating.loader.cache.path')); - - $this->assertEquals(['php', 'twig'], $container->getParameter('templating.engines'), '->registerTemplatingConfiguration() sets a templating.engines parameter'); - - $this->assertEquals(['FrameworkBundle:Form', 'theme1', 'theme2'], $container->getParameter('templating.helper.form.resources'), '->registerTemplatingConfiguration() registers the theme and adds the base theme'); - $this->assertEquals('global_hinclude_template', $container->getParameter('fragment.renderer.hinclude.global_template'), '->registerTemplatingConfiguration() registers the global hinclude.js template'); - } - - /** - * @group legacy - */ - public function testTemplatingCanBeDisabled() - { - $container = $this->createContainerFromFile('templating_disabled'); - - $this->assertFalse($container->hasParameter('templating.engines'), '"templating.engines" container parameter is not registered when templating is disabled.'); - } - public function testAssets() { $container = $this->createContainerFromFile('assets'); @@ -648,13 +559,6 @@ public function testAssetsDefaultVersionStrategyAsService() $this->assertEquals('assets.custom_version_strategy', (string) $defaultPackage->getArgument(1)); } - public function testAssetsCanBeDisabled() - { - $container = $this->createContainerFromFile('assets_disabled'); - - $this->assertFalse($container->has('templating.helper.assets'), 'The templating.helper.assets helper service is removed when assets are disabled.'); - } - public function testWebLink() { $container = $this->createContainerFromFile('web_link'); @@ -664,8 +568,6 @@ public function testWebLink() public function testMessenger() { $container = $this->createContainerFromFile('messenger'); - $this->assertTrue($container->hasAlias('message_bus')); - $this->assertTrue($container->getAlias('message_bus')->isPublic()); $this->assertTrue($container->hasAlias('messenger.default_bus')); $this->assertTrue($container->getAlias('messenger.default_bus')->isPublic()); $this->assertTrue($container->hasDefinition('messenger.transport.amqp.factory')); @@ -762,8 +664,6 @@ public function testMessengerWithMultipleBuses() ['id' => 'handle_message', 'arguments' => []], ], $container->getParameter('messenger.bus.queries.middleware')); - $this->assertTrue($container->hasAlias('message_bus')); - $this->assertSame('messenger.bus.commands', (string) $container->getAlias('message_bus')); $this->assertTrue($container->hasAlias('messenger.default_bus')); $this->assertSame('messenger.bus.commands', (string) $container->getAlias('messenger.default_bus')); } @@ -842,20 +742,6 @@ function ($directory) { $this->assertSame('Fixtures/translations', $options['cache_vary']['scanned_directories'][3]); } - /** - * @group legacy - * @expectedDeprecation Translations directory "%s/Resources/translations" is deprecated since Symfony 4.2, use "%s/translations" instead. - */ - public function testLegacyTranslationsDirectory() - { - $container = $this->createContainerFromFile('full', ['kernel.root_dir' => __DIR__.'/Fixtures']); - $options = $container->getDefinition('translator.default')->getArgument(4); - $files = array_map('realpath', $options['resource_files']['en']); - - $dir = str_replace('/', \DIRECTORY_SEPARATOR, __DIR__.'/Fixtures/Resources/translations/test_default.en.xlf'); - $this->assertContains($dir, $files, '->registerTranslatorConfiguration() finds translation resources in legacy directory'); - } - public function testTranslatorMultipleFallbacks() { $container = $this->createContainerFromFile('translator_fallbacks'); @@ -871,17 +757,6 @@ public function testTranslatorCacheDirDisabled() $this->assertNull($options['cache_dir']); } - /** - * @group legacy - */ - public function testTemplatingRequiresAtLeastOneEngine() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $container = $this->createContainer(); - $loader = new FrameworkExtension(); - $loader->load([['templating' => null]], $container); - } - public function testValidation() { $container = $this->createContainerFromFile('full'); @@ -901,11 +776,7 @@ public function testValidation() $this->assertSame('setConstraintValidatorFactory', $calls[0][0]); $this->assertEquals([new Reference('validator.validator_factory')], $calls[0][1]); $this->assertSame('setTranslator', $calls[1][0]); - if (interface_exists(TranslatorInterface::class) && class_exists(LegacyTranslatorProxy::class)) { - $this->assertEquals([new Definition(LegacyTranslatorProxy::class, [new Reference('translator', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)])], $calls[1][1]); - } else { - $this->assertEquals([new Reference('translator', ContainerInterface::IGNORE_ON_INVALID_REFERENCE)], $calls[1][1]); - } + $this->assertEquals([new Reference('translator', ContainerBuilder::IGNORE_ON_INVALID_REFERENCE)], $calls[1][1]); $this->assertSame('setTranslationDomain', $calls[2][0]); $this->assertSame(['%validator.translation_domain%'], $calls[2][1]); $this->assertSame('addXmlMappings', $calls[3][0]); @@ -1046,39 +917,6 @@ public function testValidationNoStaticMethod() // no cache, no annotations, no static methods } - /** - * @group legacy - * @expectedDeprecation The "framework.validation.strict_email" configuration key has been deprecated in Symfony 4.1. Use the "framework.validation.email_validation_mode" configuration key instead. - */ - public function testCannotConfigureStrictEmailAndEmailValidationModeAtTheSameTime() - { - $this->expectException('Symfony\Component\Config\Definition\Exception\InvalidConfigurationException'); - $this->expectExceptionMessage('"strict_email" and "email_validation_mode" cannot be used together.'); - $this->createContainerFromFile('validation_strict_email_and_validation_mode'); - } - - /** - * @group legacy - * @expectedDeprecation The "framework.validation.strict_email" configuration key has been deprecated in Symfony 4.1. Use the "framework.validation.email_validation_mode" configuration key instead. - */ - public function testEnabledStrictEmailOptionIsMappedToStrictEmailValidationMode() - { - $container = $this->createContainerFromFile('validation_strict_email_enabled'); - - $this->assertSame('strict', $container->getDefinition('validator.email')->getArgument(0)); - } - - /** - * @group legacy - * @expectedDeprecation The "framework.validation.strict_email" configuration key has been deprecated in Symfony 4.1. Use the "framework.validation.email_validation_mode" configuration key instead. - */ - public function testDisabledStrictEmailOptionIsMappedToLooseEmailValidationMode() - { - $container = $this->createContainerFromFile('validation_strict_email_disabled'); - - $this->assertSame('loose', $container->getDefinition('validator.email')->getArgument(0)); - } - public function testEmailValidationModeIsPassedToEmailValidator() { $container = $this->createContainerFromFile('validation_email_validation_mode'); @@ -1302,45 +1140,6 @@ public function testSerializerMapping() $this->assertEquals($expectedLoaders, $loaders); } - /** - * @group legacy - */ - public function testAssetHelperWhenAssetsAreEnabled() - { - $container = $this->createContainerFromFile('templating'); - $packages = $container->getDefinition('templating.helper.assets')->getArgument(0); - - $this->assertSame('assets.packages', (string) $packages); - } - - /** - * @group legacy - */ - public function testAssetHelperWhenTemplatesAreEnabledAndNoAssetsConfiguration() - { - $container = $this->createContainerFromFile('templating_no_assets'); - $packages = $container->getDefinition('templating.helper.assets')->getArgument(0); - - $this->assertSame('assets.packages', (string) $packages); - } - - /** - * @group legacy - */ - public function testAssetsHelperIsRemovedWhenPhpTemplatingEngineIsEnabledAndAssetsAreDisabled() - { - $container = $this->createContainerFromFile('templating_php_assets_disabled'); - - $this->assertTrue(!$container->has('templating.helper.assets'), 'The templating.helper.assets helper service is removed when assets are disabled.'); - } - - public function testAssetHelperWhenAssetsAndTemplatesAreDisabled() - { - $container = $this->createContainerFromFile('default_config'); - - $this->assertFalse($container->hasDefinition('templating.helper.assets')); - } - public function testSerializerServiceIsRegisteredWhenEnabled() { $container = $this->createContainerFromFile('serializer_enabled'); @@ -1580,7 +1379,6 @@ protected function createContainer(array $data = []) 'kernel.debug' => false, 'kernel.environment' => 'test', 'kernel.name' => 'kernel', - 'kernel.root_dir' => __DIR__, 'kernel.container_class' => 'testContainer', 'container.build_hash' => 'Abc1234', 'container.build_id' => hash('crc32', 'Abc123423456789'), diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php index da540da12b1f9..3218a2d5d43d7 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/DependencyInjection/PhpFrameworkExtensionTest.php @@ -81,112 +81,4 @@ public function testWorkflowValidationStateMachine() ]); }); } - - /** - * @group legacy - * @expectedDeprecation Using a workflow with type=workflow and a marking_store=single_state is deprecated since Symfony 4.3. Use type=state_machine instead. - */ - public function testWorkflowDeprecateWorkflowSingleState() - { - $this->createContainerFromClosure(function ($container) { - $container->loadFromExtension('framework', [ - 'workflows' => [ - 'article' => [ - 'type' => 'workflow', - 'marking_store' => [ - 'type' => 'single_state', - ], - 'supports' => [ - __CLASS__, - ], - 'places' => [ - 'a', - 'b', - 'c', - ], - 'transitions' => [ - 'a_to_b' => [ - 'from' => ['a'], - 'to' => ['b'], - ], - ], - ], - ], - ]); - }); - } - - /** - * @group legacy - */ - public function testWorkflowValidationMultipleState() - { - $this->createContainerFromClosure(function ($container) { - $container->loadFromExtension('framework', [ - 'workflows' => [ - 'article' => [ - 'type' => 'workflow', - 'marking_store' => [ - 'type' => 'multiple_state', - ], - 'supports' => [ - __CLASS__, - ], - 'places' => [ - 'a', - 'b', - 'c', - ], - 'transitions' => [ - 'a_to_b' => [ - 'from' => ['a'], - 'to' => ['b', 'c'], - ], - ], - ], - ], - ]); - }); - - // the test ensures that the validation does not fail (i.e. it does not throw any exceptions) - $this->addToAssertionCount(1); - } - - /** - * @group legacy - */ - public function testWorkflowValidationSingleState() - { - $this->expectException('Symfony\Component\Workflow\Exception\InvalidDefinitionException'); - $this->expectExceptionMessage('The marking store of workflow "article" can not store many places. But the transition "a_to_b" has too many output (2). Only one is accepted.'); - $this->createContainerFromClosure(function ($container) { - $container->loadFromExtension('framework', [ - 'workflows' => [ - 'article' => [ - 'type' => 'workflow', - 'marking_store' => [ - 'type' => 'single_state', - ], - 'supports' => [ - __CLASS__, - ], - 'places' => [ - 'a', - 'b', - 'c', - ], - 'transitions' => [ - 'a_to_b' => [ - 'from' => ['a'], - 'to' => ['b', 'c'], - ], - ], - ], - ], - ]); - }); - - // the test ensures that the validation does not fail (i.e. it does not throw any exceptions) - $this->addToAssertionCount(1); - } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/EventListener/ResolveControllerNameSubscriberTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/EventListener/ResolveControllerNameSubscriberTest.php deleted file mode 100644 index 362f00e95c29b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/EventListener/ResolveControllerNameSubscriberTest.php +++ /dev/null @@ -1,79 +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\Tests\EventListener; - -use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser; -use Symfony\Bundle\FrameworkBundle\EventListener\ResolveControllerNameSubscriber; -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpKernel\Event\GetResponseEvent; -use Symfony\Component\HttpKernel\Event\RequestEvent; -use Symfony\Component\HttpKernel\HttpKernelInterface; - -/** - * @group legacy - */ -class ResolveControllerNameSubscriberTest extends TestCase -{ - public function testReplacesControllerAttribute() - { - $parser = $this->getMockBuilder(ControllerNameParser::class)->disableOriginalConstructor()->getMock(); - $parser->expects($this->any()) - ->method('parse') - ->with('AppBundle:Starting:format') - ->willReturn('App\\Final\\Format::methodName'); - $httpKernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); - - $request = new Request(); - $request->attributes->set('_controller', 'AppBundle:Starting:format'); - - $subscriber = new ResolveControllerNameSubscriber($parser); - $subscriber->onKernelRequest(new RequestEvent($httpKernel, $request, HttpKernelInterface::MASTER_REQUEST)); - $this->assertEquals('App\\Final\\Format::methodName', $request->attributes->get('_controller')); - - $subscriber = new ChildResolveControllerNameSubscriber($parser); - $subscriber->onKernelRequest(new RequestEvent($httpKernel, $request, HttpKernelInterface::MASTER_REQUEST)); - $this->assertEquals('App\\Final\\Format::methodName', $request->attributes->get('_controller')); - } - - /** - * @dataProvider provideSkippedControllers - */ - public function testSkipsOtherControllerFormats($controller) - { - $parser = $this->getMockBuilder(ControllerNameParser::class)->disableOriginalConstructor()->getMock(); - $parser->expects($this->never()) - ->method('parse'); - $httpKernel = $this->getMockBuilder(HttpKernelInterface::class)->getMock(); - - $request = new Request(); - $request->attributes->set('_controller', $controller); - - $subscriber = new ResolveControllerNameSubscriber($parser); - $subscriber->onKernelRequest(new RequestEvent($httpKernel, $request, HttpKernelInterface::MASTER_REQUEST)); - $this->assertEquals($controller, $request->attributes->get('_controller')); - } - - public function provideSkippedControllers() - { - yield ['Other:format']; - yield [function () {}]; - } -} - -class ChildResolveControllerNameSubscriber extends ResolveControllerNameSubscriber -{ - public function onKernelRequest(GetResponseEvent $event) - { - parent::onKernelRequest($event); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Resources/views/translation.html.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Resources/views/translation.html.php index b8a20d246a096..7b36fba5d932b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Resources/views/translation.html.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Fixtures/Resources/views/translation.html.php @@ -26,12 +26,6 @@ trans('single-quoted key with "quote mark at the end"') ?> -transChoice( - '{0} There is no apples|{1} There is one apple|]1,Inf[ There are %count% apples', - 10, - ['%count%' => 10] -) ?> - trans('other-domain-test-no-params-short-array', [], 'not_messages'); ?> trans('other-domain-test-no-params-long-array', [], 'not_messages'); ?> @@ -40,10 +34,4 @@ trans('other-domain-test-params-long-array', ['foo' => 'bar'], 'not_messages'); ?> -transChoice('other-domain-test-trans-choice-short-array-%count%', 10, ['%count%' => 10], 'not_messages'); ?> - -transChoice('other-domain-test-trans-choice-long-array-%count%', 10, ['%count%' => 10], 'not_messages'); ?> - trans('typecast', ['a' => (int) '123'], 'not_messages'); ?> -transChoice('msg1', 10 + 1, [], 'not_messages'); ?> -transChoice('msg2', ceil(4.5), [], 'not_messages'); ?> diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/AutowiringTypesTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/AutowiringTypesTest.php index f6149ea874f8d..1d34e54d17a09 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/AutowiringTypesTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/AutowiringTypesTest.php @@ -13,12 +13,10 @@ use Doctrine\Common\Annotations\AnnotationReader; use Doctrine\Common\Annotations\CachedReader; -use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface as FrameworkBundleEngineInterface; use Symfony\Component\Cache\Adapter\FilesystemAdapter; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher; use Symfony\Component\HttpKernel\KernelInterface; -use Symfony\Component\Templating\EngineInterface as ComponentEngineInterface; class AutowiringTypesTest extends AbstractWebTestCase { @@ -38,18 +36,6 @@ public function testCachedAnnotationReaderAutowiring() $this->assertInstanceOf(CachedReader::class, $annotationReader); } - /** - * @group legacy - */ - public function testTemplatingAutowiring() - { - static::bootKernel(['root_config' => 'templating.yml', 'environment' => 'templating']); - - $autowiredServices = static::$container->get('test.autowiring_types.autowired_services'); - $this->assertInstanceOf(FrameworkBundleEngineInterface::class, $autowiredServices->getFrameworkBundleEngine()); - $this->assertInstanceOf(ComponentEngineInterface::class, $autowiredServices->getEngine()); - } - public function testEventDispatcherAutowiring() { static::bootKernel(['debug' => false]); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/AutowiringTypes/TemplatingServices.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/AutowiringTypes/TemplatingServices.php deleted file mode 100644 index 7fc0cdd7b55af..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/AutowiringTypes/TemplatingServices.php +++ /dev/null @@ -1,31 +0,0 @@ - - */ -class TemplatingServices -{ - private $frameworkBundleEngine; - private $engine; - - public function __construct(FrameworkBundleEngineInterface $frameworkBundleEngine, EngineInterface $engine) - { - $this->frameworkBundleEngine = $frameworkBundleEngine; - $this->engine = $engine; - } - - public function getFrameworkBundleEngine() - { - return $this->frameworkBundleEngine; - } - - public function getEngine() - { - return $this->engine; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/DependencyInjection/TranslationDebugPass.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/DependencyInjection/TranslationDebugPass.php deleted file mode 100644 index b8b53c25044cd..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/DependencyInjection/TranslationDebugPass.php +++ /dev/null @@ -1,21 +0,0 @@ -hasDefinition('console.command.translation_debug')) { - // skipping the /Resources/views path deprecation - $container->getDefinition('console.command.translation_debug') - ->setArgument(4, '%kernel.project_dir%/Resources/views'); - } - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/Slugger/SlugConstructArgService.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/Slugger/SlugConstructArgService.php new file mode 100644 index 0000000000000..943fda4b6b9e0 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/Slugger/SlugConstructArgService.php @@ -0,0 +1,29 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Slugger; + +use Symfony\Component\String\Slugger\SluggerInterface; + +class SlugConstructArgService +{ + private $slugger; + + public function __construct(SluggerInterface $slugger) + { + $this->slugger = $slugger; + } + + public function hello(): string + { + return $this->slugger->slug('Стойността трябва да бъде лъжа'); + } +} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/TestBundle.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/TestBundle.php index d0fb6ee0daa28..df55260d8c607 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/TestBundle.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/Bundle/TestBundle/TestBundle.php @@ -13,9 +13,7 @@ use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\DependencyInjection\AnnotationReaderPass; use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\DependencyInjection\Config\CustomConfig; -use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\DependencyInjection\TranslationDebugPass; use Symfony\Component\DependencyInjection\Compiler\CheckTypeDeclarationsPass; -use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Compiler\PassConfig; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag; @@ -39,16 +37,6 @@ public function build(ContainerBuilder $container) $extension->setCustomConfig(new CustomConfig()); $container->addCompilerPass(new AnnotationReaderPass(), PassConfig::TYPE_AFTER_REMOVING); - $container->addCompilerPass(new TranslationDebugPass()); - - $container->addCompilerPass(new class() implements CompilerPassInterface { - public function process(ContainerBuilder $container) - { - $container->removeDefinition('twig.controller.exception'); - $container->removeDefinition('twig.controller.preview_error'); - } - }); - $container->addCompilerPass(new CheckTypeDeclarationsPass(true, ['http_client', '.debug.http_client']), PassConfig::TYPE_AFTER_REMOVING, -100); } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/SluggerLocaleAwareTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/SluggerLocaleAwareTest.php new file mode 100644 index 0000000000000..d8552977c0835 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/SluggerLocaleAwareTest.php @@ -0,0 +1,31 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bundle\FrameworkBundle\Tests\Functional; + +/** + * @group functional + */ +class SluggerLocaleAwareTest extends AbstractWebTestCase +{ + /** + * @requires extension intl + */ + public function testLocalizedSlugger() + { + $kernel = static::createKernel(['test_case' => 'Slugger', 'root_config' => 'config.yml']); + $kernel->boot(); + + $service = $kernel->getContainer()->get('Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Slugger\SlugConstructArgService'); + + $this->assertSame('Stoinostta-tryabva-da-bude-luzha', $service->hello()); + } +} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/AutowiringTypes/templating.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/AutowiringTypes/templating.yml deleted file mode 100644 index 765bfa9d70d48..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/AutowiringTypes/templating.yml +++ /dev/null @@ -1,12 +0,0 @@ -imports: - - { resource: ../config/default.yml } - -services: - _defaults: { public: true } - test.autowiring_types.autowired_services: - class: Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\AutowiringTypes\TemplatingServices - autowire: true - -framework: - templating: - engines: ['php'] diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/BundlePaths/config.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/BundlePaths/config.yml index 3e1e53738cf93..94994ba60c798 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/BundlePaths/config.yml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/BundlePaths/config.yml @@ -8,4 +8,3 @@ framework: twig: strict_variables: '%kernel.debug%' - exception_controller: null # to be removed in 5.0 diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Fragment/config.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Fragment/config.yml index ceeea37a1001b..16fc81dd268d4 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Fragment/config.yml +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Fragment/config.yml @@ -7,4 +7,3 @@ framework: twig: strict_variables: '%kernel.debug%' - exception_controller: null # to be removed in 5.0 diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Slugger/bundles.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Slugger/bundles.php new file mode 100644 index 0000000000000..15ff182c6fed5 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Slugger/bundles.php @@ -0,0 +1,18 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Bundle\FrameworkBundle\FrameworkBundle; +use Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\TestBundle; + +return [ + new FrameworkBundle(), + new TestBundle(), +]; diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Slugger/config.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Slugger/config.yml new file mode 100644 index 0000000000000..f80091b831e05 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Slugger/config.yml @@ -0,0 +1,14 @@ +imports: + - { resource: ../config/default.yml } + - { resource: services.yml } + +framework: + secret: '%secret%' + default_locale: '%env(LOCALE)%' + translator: + fallbacks: + - '%env(LOCALE)%' + +parameters: + env(LOCALE): bg + secret: test diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Slugger/services.yml b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Slugger/services.yml new file mode 100644 index 0000000000000..b446d60a13b57 --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Functional/app/Slugger/services.yml @@ -0,0 +1,6 @@ +services: + _defaults: + public: true + + Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Slugger\SlugConstructArgService: + arguments: ['@slugger'] diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel/ConcreteMicroKernel.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel/ConcreteMicroKernel.php index b2a84ed536863..a017da9bc18e9 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel/ConcreteMicroKernel.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel/ConcreteMicroKernel.php @@ -22,7 +22,7 @@ use Symfony\Component\HttpKernel\Event\ExceptionEvent; use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\HttpKernel\KernelEvents; -use Symfony\Component\Routing\RouteCollectionBuilder; +use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator; class ConcreteMicroKernel extends Kernel implements EventSubscriberInterface { @@ -80,10 +80,10 @@ public function __destruct() $fs->remove($this->cacheDir); } - protected function configureRoutes(RouteCollectionBuilder $routes) + protected function configureRouting(RoutingConfigurator $routes): void { - $routes->add('/', 'kernel::halloweenAction'); - $routes->add('/danger', 'kernel::dangerousAction'); + $routes->add('halloween', '/')->controller('kernel::halloweenAction'); + $routes->add('danger', '/danger')->controller('kernel::dangerousAction'); } protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader) diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel/MicroKernelTraitTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel/MicroKernelTraitTest.php index dd909ea6fc8ce..a66ebeffdcc3b 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel/MicroKernelTraitTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel/MicroKernelTraitTest.php @@ -19,6 +19,18 @@ class MicroKernelTraitTest extends TestCase { + /** + * @group legacy + * @expectedDeprecation Adding routes via the "Symfony\Bundle\FrameworkBundle\Tests\Kernel\MicroKernelWithConfigureRoutes:configureRoutes()" method is deprecated since Symfony 5.1 and will have no effect in 6.0; use "configureRouting()" instead. + * @expectedDeprecation Not overriding the "Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait::configureRouting()" method is deprecated since Symfony 5.1 and will trigger a fatal error in 6.0. + */ + public function testConfigureRoutingDeprecated() + { + $kernel = new MicroKernelWithConfigureRoutes('test', false); + $kernel->boot(); + $kernel->handle(Request::create('/')); + } + public function test() { $kernel = new ConcreteMicroKernel('test', false); diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel/MicroKernelWithConfigureRoutes.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel/MicroKernelWithConfigureRoutes.php new file mode 100644 index 0000000000000..b57f301ee6c4c --- /dev/null +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Kernel/MicroKernelWithConfigureRoutes.php @@ -0,0 +1,74 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Bundle\FrameworkBundle\Tests\Kernel; + +use Psr\Log\NullLogger; +use Symfony\Bundle\FrameworkBundle\FrameworkBundle; +use Symfony\Bundle\FrameworkBundle\Kernel\MicroKernelTrait; +use Symfony\Component\Config\Loader\LoaderInterface; +use Symfony\Component\DependencyInjection\ContainerBuilder; +use Symfony\Component\Filesystem\Filesystem; +use Symfony\Component\HttpKernel\Kernel; +use Symfony\Component\Routing\RouteCollectionBuilder; + +class MicroKernelWithConfigureRoutes extends Kernel +{ + use MicroKernelTrait; + + private $cacheDir; + + public function registerBundles(): iterable + { + return [ + new FrameworkBundle(), + ]; + } + + public function getCacheDir(): string + { + return $this->cacheDir = sys_get_temp_dir().'/sf_micro_kernel_with_configured_routes'; + } + + public function getLogDir(): string + { + return $this->cacheDir; + } + + public function __sleep(): array + { + throw new \BadMethodCallException('Cannot serialize '.__CLASS__); + } + + public function __wakeup() + { + throw new \BadMethodCallException('Cannot unserialize '.__CLASS__); + } + + public function __destruct() + { + $fs = new Filesystem(); + $fs->remove($this->cacheDir); + } + + protected function configureRoutes(RouteCollectionBuilder $routes) + { + $routes->add('/', 'kernel::halloweenAction'); + } + + protected function configureContainer(ContainerBuilder $c, LoaderInterface $loader) + { + $c->register('logger', NullLogger::class); + $c->loadFromExtension('framework', [ + 'secret' => '$ecret', + ]); + } +} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/DelegatingLoaderTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/DelegatingLoaderTest.php index daed030f721a2..de7f91ee637a7 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/DelegatingLoaderTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/DelegatingLoaderTest.php @@ -3,7 +3,6 @@ namespace Symfony\Bundle\FrameworkBundle\Tests\Routing; use PHPUnit\Framework\TestCase; -use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser; use Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\Config\Loader\LoaderResolver; @@ -13,17 +12,10 @@ class DelegatingLoaderTest extends TestCase { - /** - * @group legacy - * @expectedDeprecation Passing a "Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser" instance as first argument to "Symfony\Bundle\FrameworkBundle\Routing\DelegatingLoader::__construct()" is deprecated since Symfony 4.4, pass a "Symfony\Component\Config\Loader\LoaderResolverInterface" instance instead. - */ public function testConstructorApi() { - $controllerNameParser = $this->getMockBuilder(ControllerNameParser::class) - ->disableOriginalConstructor() - ->getMock(); - new DelegatingLoader($controllerNameParser, new LoaderResolver()); - $this->assertTrue(true, '__construct() takes a ControllerNameParser and LoaderResolverInterface respectively as its first and second argument.'); + new DelegatingLoader(new LoaderResolver()); + $this->assertTrue(true, '__construct() takeS a LoaderResolverInterface as its first argument.'); } public function testLoadDefaultOptions() @@ -64,47 +56,4 @@ public function testLoadDefaultOptions() ]; $this->assertSame($expected, $routeCollection->get('bar')->getOptions()); } - - /** - * @group legacy - * @expectedDeprecation Referencing controllers with foo:bar:baz is deprecated since Symfony 4.1, use "some_parsed::controller" instead. - */ - public function testLoad() - { - $controllerNameParser = $this->getMockBuilder(ControllerNameParser::class) - ->disableOriginalConstructor() - ->getMock(); - - $controllerNameParser->expects($this->once()) - ->method('parse') - ->with('foo:bar:baz') - ->willReturn('some_parsed::controller'); - - $loaderResolver = $this->getMockBuilder(LoaderResolverInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $loader = $this->getMockBuilder(LoaderInterface::class)->getMock(); - - $loaderResolver->expects($this->once()) - ->method('resolve') - ->willReturn($loader); - - $routeCollection = new RouteCollection(); - $routeCollection->add('foo', new Route('/', ['_controller' => 'foo:bar:baz'])); - $routeCollection->add('bar', new Route('/', ['_controller' => 'foo::baz'])); - $routeCollection->add('baz', new Route('/', ['_controller' => 'foo:baz'])); - - $loader->expects($this->once()) - ->method('load') - ->willReturn($routeCollection); - - $delegatingLoader = new DelegatingLoader($controllerNameParser, $loaderResolver); - - $loadedRouteCollection = $delegatingLoader->load('foo'); - $this->assertCount(3, $loadedRouteCollection); - $this->assertSame('some_parsed::controller', $routeCollection->get('foo')->getDefault('_controller')); - $this->assertSame('foo::baz', $routeCollection->get('bar')->getDefault('_controller')); - $this->assertSame('foo:baz', $routeCollection->get('baz')->getDefault('_controller')); - } } diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/LegacyRouteLoaderContainerTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/LegacyRouteLoaderContainerTest.php deleted file mode 100644 index b0492efd89da4..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/LegacyRouteLoaderContainerTest.php +++ /dev/null @@ -1,68 +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\Tests\Routing; - -use PHPUnit\Framework\TestCase; -use Psr\Container\ContainerInterface; -use Symfony\Bundle\FrameworkBundle\Routing\LegacyRouteLoaderContainer; -use Symfony\Component\DependencyInjection\Container; - -/** - * @group legacy - */ -class LegacyRouteLoaderContainerTest extends TestCase -{ - /** - * @var ContainerInterface - */ - private $container; - - /** - * @var ContainerInterface - */ - private $serviceLocator; - - /** - * @var LegacyRouteLoaderContainer - */ - private $legacyRouteLoaderContainer; - - /** - * {@inheritdoc} - */ - protected function setUp(): void - { - $this->container = new Container(); - $this->container->set('foo', new \stdClass()); - - $this->serviceLocator = new Container(); - $this->serviceLocator->set('bar', new \stdClass()); - - $this->legacyRouteLoaderContainer = new LegacyRouteLoaderContainer($this->container, $this->serviceLocator); - } - - /** - * @expectedDeprecation Registering the service route loader "foo" without tagging it with the "routing.route_loader" tag is deprecated since Symfony 4.4 and will be required in Symfony 5.0. - */ - public function testGet() - { - $this->assertSame($this->container->get('foo'), $this->legacyRouteLoaderContainer->get('foo')); - $this->assertSame($this->serviceLocator->get('bar'), $this->legacyRouteLoaderContainer->get('bar')); - } - - public function testHas() - { - $this->assertTrue($this->legacyRouteLoaderContainer->has('foo')); - $this->assertTrue($this->legacyRouteLoaderContainer->has('bar')); - $this->assertFalse($this->legacyRouteLoaderContainer->has('ccc')); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RedirectableUrlMatcherTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RedirectableUrlMatcherTest.php deleted file mode 100644 index 1c11cf9e09024..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Routing/RedirectableUrlMatcherTest.php +++ /dev/null @@ -1,64 +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\Tests\Routing; - -use PHPUnit\Framework\TestCase; -use Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher; -use Symfony\Component\Routing\RequestContext; -use Symfony\Component\Routing\Route; -use Symfony\Component\Routing\RouteCollection; - -/** - * @group legacy - */ -class RedirectableUrlMatcherTest extends TestCase -{ - public function testRedirectWhenNoSlash() - { - $coll = new RouteCollection(); - $coll->add('foo', new Route('/foo/')); - - $matcher = new RedirectableUrlMatcher($coll, $context = new RequestContext()); - - $this->assertEquals([ - '_controller' => 'Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction', - 'path' => '/foo/', - 'permanent' => true, - 'scheme' => null, - 'httpPort' => $context->getHttpPort(), - 'httpsPort' => $context->getHttpsPort(), - '_route' => 'foo', - ], - $matcher->match('/foo') - ); - } - - public function testSchemeRedirect() - { - $coll = new RouteCollection(); - $coll->add('foo', new Route('/foo', [], [], [], '', ['https'])); - - $matcher = new RedirectableUrlMatcher($coll, $context = new RequestContext()); - - $this->assertEquals([ - '_controller' => 'Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction', - 'path' => '/foo', - 'permanent' => true, - 'scheme' => 'https', - 'httpPort' => $context->getHttpPort(), - 'httpsPort' => $context->getHttpsPort(), - '_route' => 'foo', - ], - $matcher->match('/foo') - ); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/DelegatingEngineTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/DelegatingEngineTest.php deleted file mode 100644 index 3445ecde3253c..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/DelegatingEngineTest.php +++ /dev/null @@ -1,126 +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\Tests\Templating; - -use PHPUnit\Framework\TestCase; -use Symfony\Bundle\FrameworkBundle\Templating\DelegatingEngine; -use Symfony\Component\HttpFoundation\Response; - -/** - * @group legacy - */ -class DelegatingEngineTest extends TestCase -{ - public function testSupportsRetrievesEngineFromTheContainer() - { - $container = $this->getContainerMock([ - 'engine.first' => $this->getEngineMock('template.php', false), - 'engine.second' => $this->getEngineMock('template.php', true), - ]); - - $delegatingEngine = new DelegatingEngine($container, ['engine.first', 'engine.second']); - - $this->assertTrue($delegatingEngine->supports('template.php')); - } - - public function testGetExistingEngine() - { - $firstEngine = $this->getEngineMock('template.php', false); - $secondEngine = $this->getEngineMock('template.php', true); - $container = $this->getContainerMock([ - 'engine.first' => $firstEngine, - 'engine.second' => $secondEngine, - ]); - - $delegatingEngine = new DelegatingEngine($container, ['engine.first', 'engine.second']); - - $this->assertSame($secondEngine, $delegatingEngine->getEngine('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([ - 'engine.first' => $firstEngine, - 'engine.second' => $secondEngine, - ]); - - $delegatingEngine = new DelegatingEngine($container, ['engine.first', 'engine.second']); - $delegatingEngine->getEngine('template.php'); - } - - public function testRenderResponseWithFrameworkEngine() - { - $response = new Response(); - $engine = $this->getFrameworkEngineMock('template.php', true); - $engine->expects($this->once()) - ->method('renderResponse') - ->with('template.php', ['foo' => 'bar']) - ->willReturn($response); - $container = $this->getContainerMock(['engine' => $engine]); - - $delegatingEngine = new DelegatingEngine($container, ['engine']); - - $this->assertSame($response, $delegatingEngine->renderResponse('template.php', ['foo' => 'bar'])); - } - - public function testRenderResponseWithTemplatingEngine() - { - $engine = $this->getEngineMock('template.php', true); - $container = $this->getContainerMock(['engine' => $engine]); - $delegatingEngine = new DelegatingEngine($container, ['engine']); - - $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $delegatingEngine->renderResponse('template.php', ['foo' => 'bar'])); - } - - private function getEngineMock($template, $supports) - { - $engine = $this->getMockBuilder('Symfony\Component\Templating\EngineInterface')->getMock(); - - $engine->expects($this->once()) - ->method('supports') - ->with($template) - ->willReturn($supports); - - return $engine; - } - - private function getFrameworkEngineMock($template, $supports) - { - $engine = $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\EngineInterface')->getMock(); - - $engine->expects($this->once()) - ->method('supports') - ->with($template) - ->willReturn($supports); - - return $engine; - } - - private function getContainerMock($services) - { - $container = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerInterface')->getMock(); - - $i = 0; - foreach ($services as $id => $service) { - $container->expects($this->at($i++)) - ->method('get') - ->with($id) - ->willReturn($service); - } - - return $container; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/GlobalVariablesTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/GlobalVariablesTest.php deleted file mode 100644 index a892ebeddc74b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/GlobalVariablesTest.php +++ /dev/null @@ -1,109 +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\Tests\Templating; - -use Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables; -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; -use Symfony\Component\DependencyInjection\Container; - -/** - * @group legacy - */ -class GlobalVariablesTest extends TestCase -{ - private $container; - private $globals; - - protected function setUp(): void - { - $this->container = new Container(); - $this->globals = new GlobalVariables($this->container); - } - - public function testGetTokenNoTokenStorage() - { - $this->assertNull($this->globals->getToken()); - } - - public function testGetTokenNoToken() - { - $tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(); - $this->container->set('security.token_storage', $tokenStorage); - $this->assertNull($this->globals->getToken()); - } - - public function testGetToken() - { - $tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(); - - $this->container->set('security.token_storage', $tokenStorage); - - $tokenStorage - ->expects($this->once()) - ->method('getToken') - ->willReturn('token'); - - $this->assertSame('token', $this->globals->getToken()); - } - - public function testGetUserNoTokenStorage() - { - $this->assertNull($this->globals->getUser()); - } - - public function testGetUserNoToken() - { - $tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(); - $this->container->set('security.token_storage', $tokenStorage); - $this->assertNull($this->globals->getUser()); - } - - /** - * @dataProvider getUserProvider - */ - public function testGetUser($user, $expectedUser) - { - $tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(); - $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock(); - - $this->container->set('security.token_storage', $tokenStorage); - - $token - ->expects($this->once()) - ->method('getUser') - ->willReturn($user); - - $tokenStorage - ->expects($this->once()) - ->method('getToken') - ->willReturn($token); - - $this->assertSame($expectedUser, $this->globals->getUser()); - } - - public function getUserProvider() - { - $user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock(); - $std = new \stdClass(); - $token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock(); - - return [ - [$user, $user], - [$std, $std], - [$token, $token], - ['Anon.', null], - [null, null], - [10, null], - [true, null], - ]; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/AssetsHelperTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/AssetsHelperTest.php deleted file mode 100644 index 8861ff6eb9ff6..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/AssetsHelperTest.php +++ /dev/null @@ -1,48 +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\Tests\Templating\Helper; - -use PHPUnit\Framework\TestCase; -use Symfony\Bundle\FrameworkBundle\Templating\Helper\AssetsHelper; -use Symfony\Component\Asset\Package; -use Symfony\Component\Asset\Packages; -use Symfony\Component\Asset\VersionStrategy\StaticVersionStrategy; - -/** - * @group legacy - */ -class AssetsHelperTest extends TestCase -{ - private $helper; - - protected function setUp(): void - { - $fooPackage = new Package(new StaticVersionStrategy('42', '%s?v=%s')); - $barPackage = new Package(new StaticVersionStrategy('22', '%s?%s')); - - $packages = new Packages($fooPackage, ['bar' => $barPackage]); - - $this->helper = new AssetsHelper($packages); - } - - public function testGetUrl() - { - $this->assertEquals('me.png?v=42', $this->helper->getUrl('me.png')); - $this->assertEquals('me.png?22', $this->helper->getUrl('me.png', 'bar')); - } - - public function testGetVersion() - { - $this->assertEquals('42', $this->helper->getVersion('/')); - $this->assertEquals('22', $this->helper->getVersion('/', 'bar')); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Fixtures/StubTemplateNameParser.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Fixtures/StubTemplateNameParser.php deleted file mode 100644 index e6b8105806c71..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Fixtures/StubTemplateNameParser.php +++ /dev/null @@ -1,44 +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\Tests\Templating\Helper\Fixtures; - -use Symfony\Component\Templating\TemplateNameParserInterface; -use Symfony\Component\Templating\TemplateReference; -use Symfony\Component\Templating\TemplateReferenceInterface; - -class StubTemplateNameParser implements TemplateNameParserInterface -{ - private $root; - - private $rootTheme; - - public function __construct($root, $rootTheme) - { - $this->root = $root; - $this->rootTheme = $rootTheme; - } - - public function parse($name): TemplateReferenceInterface - { - list($bundle, $controller, $template) = explode(':', $name, 3); - - if ('_' == $template[0]) { - $path = $this->rootTheme.'/Custom/'.$template; - } elseif ('TestBundle' === $bundle) { - $path = $this->rootTheme.'/'.$controller.'/'.$template; - } else { - $path = $this->root.'/'.$controller.'/'.$template; - } - - return new TemplateReference($path, 'php'); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Fixtures/StubTranslator.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Fixtures/StubTranslator.php deleted file mode 100644 index 2f051f035e548..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Fixtures/StubTranslator.php +++ /dev/null @@ -1,22 +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\Tests\Templating\Helper\Fixtures; - -use Symfony\Contracts\Translation\TranslatorInterface; - -class StubTranslator implements TranslatorInterface -{ - public function trans($id, array $parameters = [], $domain = null, $locale = null): string - { - return '[trans]'.strtr($id, $parameters).'[/trans]'; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php deleted file mode 100644 index c277cf8e06884..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperDivLayoutTest.php +++ /dev/null @@ -1,264 +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\Tests\Templating\Helper; - -use Symfony\Bundle\FrameworkBundle\Templating\Helper\TranslatorHelper; -use Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper\Fixtures\StubTemplateNameParser; -use Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper\Fixtures\StubTranslator; -use Symfony\Component\Form\Extension\Templating\TemplatingExtension; -use Symfony\Component\Form\FormView; -use Symfony\Component\Form\Tests\AbstractDivLayoutTest; -use Symfony\Component\Templating\Loader\FilesystemLoader; -use Symfony\Component\Templating\PhpEngine; - -/** - * @group legacy - */ -class FormHelperDivLayoutTest extends AbstractDivLayoutTest -{ - /** - * @var PhpEngine - */ - protected $engine; - - protected static $supportedFeatureSetVersion = 404; - - protected function getExtensions() - { - // should be moved to the Form component once absolute file paths are supported - // by the default name parser in the Templating component - $reflClass = new \ReflectionClass('Symfony\Bundle\FrameworkBundle\FrameworkBundle'); - $root = realpath(\dirname($reflClass->getFileName()).'/Resources/views'); - $rootTheme = realpath(__DIR__.'/Resources'); - $templateNameParser = new StubTemplateNameParser($root, $rootTheme); - $loader = new FilesystemLoader([]); - - $this->engine = new PhpEngine($templateNameParser, $loader); - $this->engine->addGlobal('global', ''); - $this->engine->setHelpers([ - new TranslatorHelper(new StubTranslator()), - ]); - - return array_merge(parent::getExtensions(), [ - new TemplatingExtension($this->engine, $this->csrfTokenManager, [ - 'FrameworkBundle:Form', - ]), - ]); - } - - protected function tearDown(): void - { - $this->engine = null; - - parent::tearDown(); - } - - public function testStartTagHasNoActionAttributeWhenActionIsEmpty() - { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'method' => 'get', - 'action' => '', - ]); - - $html = $this->renderStart($form->createView()); - - $this->assertSame('', $html); - } - - public function testStartTagHasActionAttributeWhenActionIsZero() - { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'method' => 'get', - 'action' => '0', - ]); - - $html = $this->renderStart($form->createView()); - - $this->assertSame('', $html); - } - - public function testMoneyWidgetInIso() - { - $this->engine->setCharset('ISO-8859-1'); - - $view = $this->factory - ->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\MoneyType') - ->createView() - ; - - $this->assertSame('€ ', $this->renderWidget($view)); - } - - public function testHelpAttr() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'help' => 'Help text test!', - 'help_attr' => [ - 'class' => 'class-test', - ], - ]); - $view = $form->createView(); - $html = $this->renderHelp($view); - - $this->assertMatchesXpath($html, - '/p - [@id="name_help"] - [@class="class-test help-text"] - [.="[trans]Help text test![/trans]"] -' - ); - } - - public function testHelpHtmlDefaultIsFalse() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'help' => 'Help text test!', - ]); - $view = $form->createView(); - $html = $this->renderHelp($view); - - $this->assertMatchesXpath($html, - '/p - [@id="name_help"] - [@class="help-text"] - [.="[trans]Help text test![/trans]"] -' - ); - - $this->assertMatchesXpath($html, - '/p - [@id="name_help"] - [@class="help-text"] - /b - [.="text"] -', 0 - ); - } - - public function testHelpHtmlIsFalse() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'help' => 'Help text test!', - 'help_html' => false, - ]); - $view = $form->createView(); - $html = $this->renderHelp($view); - - $this->assertMatchesXpath($html, - '/p - [@id="name_help"] - [@class="help-text"] - [.="[trans]Help text test![/trans]"] -' - ); - - $this->assertMatchesXpath($html, - '/p - [@id="name_help"] - [@class="help-text"] - /b - [.="text"] -', 0 - ); - } - - public function testHelpHtmlIsTrue() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'help' => 'Help text test!', - 'help_html' => true, - ]); - $view = $form->createView(); - $html = $this->renderHelp($view); - - $this->assertMatchesXpath($html, - '/p - [@id="name_help"] - [@class="help-text"] - [.="[trans]Help text test![/trans]"] -', 0 - ); - - $this->assertMatchesXpath($html, - '/p - [@id="name_help"] - [@class="help-text"] - /b - [.="text"] -' - ); - } - - protected function renderForm(FormView $view, array $vars = []) - { - return (string) $this->engine->get('form')->form($view, $vars); - } - - protected function renderLabel(FormView $view, $label = null, array $vars = []) - { - return (string) $this->engine->get('form')->label($view, $label, $vars); - } - - protected function renderHelp(FormView $view) - { - return (string) $this->engine->get('form')->help($view); - } - - protected function renderErrors(FormView $view) - { - return (string) $this->engine->get('form')->errors($view); - } - - protected function renderWidget(FormView $view, array $vars = []) - { - return (string) $this->engine->get('form')->widget($view, $vars); - } - - protected function renderRow(FormView $view, array $vars = []) - { - return (string) $this->engine->get('form')->row($view, $vars); - } - - protected function renderRest(FormView $view, array $vars = []) - { - return (string) $this->engine->get('form')->rest($view, $vars); - } - - protected function renderStart(FormView $view, array $vars = []) - { - return (string) $this->engine->get('form')->start($view, $vars); - } - - protected function renderEnd(FormView $view, array $vars = []) - { - return (string) $this->engine->get('form')->end($view, $vars); - } - - protected function setTheme(FormView $view, array $themes, $useDefaultThemes = true) - { - $this->engine->get('form')->setTheme($view, $themes, $useDefaultThemes); - } - - public static function themeBlockInheritanceProvider() - { - return [ - [['TestBundle:Parent']], - ]; - } - - public static function themeInheritanceProvider() - { - return [ - [['TestBundle:Parent'], ['TestBundle:Child']], - ]; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php deleted file mode 100644 index e2c21f8bdd15c..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/FormHelperTableLayoutTest.php +++ /dev/null @@ -1,159 +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\Tests\Templating\Helper; - -use Symfony\Bundle\FrameworkBundle\Templating\Helper\TranslatorHelper; -use Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper\Fixtures\StubTemplateNameParser; -use Symfony\Bundle\FrameworkBundle\Tests\Templating\Helper\Fixtures\StubTranslator; -use Symfony\Component\Form\Extension\Templating\TemplatingExtension; -use Symfony\Component\Form\FormView; -use Symfony\Component\Form\Tests\AbstractTableLayoutTest; -use Symfony\Component\Templating\Loader\FilesystemLoader; -use Symfony\Component\Templating\PhpEngine; - -/** - * @group legacy - */ -class FormHelperTableLayoutTest extends AbstractTableLayoutTest -{ - /** - * @var PhpEngine - */ - protected $engine; - - protected static $supportedFeatureSetVersion = 404; - - public function testStartTagHasNoActionAttributeWhenActionIsEmpty() - { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'method' => 'get', - 'action' => '', - ]); - - $html = $this->renderStart($form->createView()); - - $this->assertSame('', $html); - } - - public function testStartTagHasActionAttributeWhenActionIsZero() - { - $form = $this->factory->create('Symfony\Component\Form\Extension\Core\Type\FormType', null, [ - 'method' => 'get', - 'action' => '0', - ]); - - $html = $this->renderStart($form->createView()); - - $this->assertSame('', $html); - } - - public function testHelpAttr() - { - $form = $this->factory->createNamed('name', 'Symfony\Component\Form\Extension\Core\Type\TextType', null, [ - 'help' => 'Help text test!', - 'help_attr' => [ - 'class' => 'class-test', - ], - ]); - $view = $form->createView(); - $html = $this->renderHelp($view); - - $this->assertMatchesXpath($html, - '/p - [@id="name_help"] - [@class="class-test help-text"] - [.="[trans]Help text test![/trans]"] -' - ); - } - - protected function getExtensions() - { - // should be moved to the Form component once absolute file paths are supported - // by the default name parser in the Templating component - $reflClass = new \ReflectionClass('Symfony\Bundle\FrameworkBundle\FrameworkBundle'); - $root = realpath(\dirname($reflClass->getFileName()).'/Resources/views'); - $rootTheme = realpath(__DIR__.'/Resources'); - $templateNameParser = new StubTemplateNameParser($root, $rootTheme); - $loader = new FilesystemLoader([]); - - $this->engine = new PhpEngine($templateNameParser, $loader); - $this->engine->addGlobal('global', ''); - $this->engine->setHelpers([ - new TranslatorHelper(new StubTranslator()), - ]); - - return array_merge(parent::getExtensions(), [ - new TemplatingExtension($this->engine, $this->csrfTokenManager, [ - 'FrameworkBundle:Form', - 'FrameworkBundle:FormTable', - ]), - ]); - } - - protected function tearDown(): void - { - $this->engine = null; - - parent::tearDown(); - } - - protected function renderForm(FormView $view, array $vars = []) - { - return (string) $this->engine->get('form')->form($view, $vars); - } - - protected function renderLabel(FormView $view, $label = null, array $vars = []) - { - return (string) $this->engine->get('form')->label($view, $label, $vars); - } - - protected function renderHelp(FormView $view) - { - return (string) $this->engine->get('form')->help($view); - } - - protected function renderErrors(FormView $view) - { - return (string) $this->engine->get('form')->errors($view); - } - - protected function renderWidget(FormView $view, array $vars = []) - { - return (string) $this->engine->get('form')->widget($view, $vars); - } - - protected function renderRow(FormView $view, array $vars = []) - { - return (string) $this->engine->get('form')->row($view, $vars); - } - - protected function renderRest(FormView $view, array $vars = []) - { - return (string) $this->engine->get('form')->rest($view, $vars); - } - - protected function renderStart(FormView $view, array $vars = []) - { - return (string) $this->engine->get('form')->start($view, $vars); - } - - protected function renderEnd(FormView $view, array $vars = []) - { - return (string) $this->engine->get('form')->end($view, $vars); - } - - protected function setTheme(FormView $view, array $themes, $useDefaultThemes = true) - { - $this->engine->get('form')->setTheme($view, $themes, $useDefaultThemes); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/RequestHelperTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/RequestHelperTest.php deleted file mode 100644 index cddb14e5f9df9..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/RequestHelperTest.php +++ /dev/null @@ -1,57 +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\Tests\Templating\Helper; - -use PHPUnit\Framework\TestCase; -use Symfony\Bundle\FrameworkBundle\Templating\Helper\RequestHelper; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\RequestStack; - -/** - * @group legacy - */ -class RequestHelperTest extends TestCase -{ - protected $requestStack; - - protected function setUp(): void - { - $this->requestStack = new RequestStack(); - $request = new Request(); - $request->initialize(['foobar' => 'bar']); - $this->requestStack->push($request); - } - - public function testGetParameter() - { - $helper = new RequestHelper($this->requestStack); - - $this->assertEquals('bar', $helper->getParameter('foobar')); - $this->assertEquals('foo', $helper->getParameter('bar', 'foo')); - - $this->assertNull($helper->getParameter('foo')); - } - - public function testGetLocale() - { - $helper = new RequestHelper($this->requestStack); - - $this->assertEquals('en', $helper->getLocale()); - } - - public function testGetName() - { - $helper = new RequestHelper($this->requestStack); - - $this->assertEquals('request', $helper->getName()); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Child/form_label.html.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Child/form_label.html.php deleted file mode 100644 index aebb53d3e7221..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Child/form_label.html.php +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_name_c_entry_label.html.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_name_c_entry_label.html.php deleted file mode 100644 index 4ad7e75ddcc12..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_name_c_entry_label.html.php +++ /dev/null @@ -1,2 +0,0 @@ -humanize($name); } ?> - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_names_entry_label.html.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_names_entry_label.html.php deleted file mode 100644 index 71de9d4631de7..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_names_entry_label.html.php +++ /dev/null @@ -1,4 +0,0 @@ -humanize($name); -} ?> - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_text_id_widget.html.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_text_id_widget.html.php deleted file mode 100644 index 078fe57583f1c..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Custom/_text_id_widget.html.php +++ /dev/null @@ -1,3 +0,0 @@ -
- widget($form) ?> -
diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Parent/form_label.html.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Parent/form_label.html.php deleted file mode 100644 index 068c5dec3ff48..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Parent/form_label.html.php +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Parent/form_widget_simple.html.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Parent/form_widget_simple.html.php deleted file mode 100644 index 1b53a7213f025..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/Resources/Parent/form_widget_simple.html.php +++ /dev/null @@ -1,2 +0,0 @@ - -block($form, 'widget_attributes'); ?> value="" rel="theme" /> diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/SessionHelperTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/SessionHelperTest.php deleted file mode 100644 index 0ee9930efddf2..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/SessionHelperTest.php +++ /dev/null @@ -1,78 +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\Tests\Templating\Helper; - -use PHPUnit\Framework\TestCase; -use Symfony\Bundle\FrameworkBundle\Templating\Helper\SessionHelper; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Component\HttpFoundation\Session\Session; -use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; - -/** - * @group legacy - */ -class SessionHelperTest extends TestCase -{ - protected $requestStack; - - protected function setUp(): void - { - $request = new Request(); - - $session = new Session(new MockArraySessionStorage()); - $session->set('foobar', 'bar'); - $session->getFlashBag()->set('notice', 'bar'); - - $request->setSession($session); - - $this->requestStack = new RequestStack(); - $this->requestStack->push($request); - } - - protected function tearDown(): void - { - $this->requestStack = null; - } - - public function testFlash() - { - $helper = new SessionHelper($this->requestStack); - - $this->assertTrue($helper->hasFlash('notice')); - - $this->assertEquals(['bar'], $helper->getFlash('notice')); - } - - public function testGetFlashes() - { - $helper = new SessionHelper($this->requestStack); - $this->assertEquals(['notice' => ['bar']], $helper->getFlashes()); - } - - public function testGet() - { - $helper = new SessionHelper($this->requestStack); - - $this->assertEquals('bar', $helper->get('foobar')); - $this->assertEquals('foo', $helper->get('bar', 'foo')); - - $this->assertNull($helper->get('foo')); - } - - public function testGetName() - { - $helper = new SessionHelper($this->requestStack); - - $this->assertEquals('session', $helper->getName()); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/StopwatchHelperTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/StopwatchHelperTest.php deleted file mode 100644 index f5030b4e79fc1..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Helper/StopwatchHelperTest.php +++ /dev/null @@ -1,42 +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\Tests\Templating\Helper; - -use PHPUnit\Framework\TestCase; -use Symfony\Bundle\FrameworkBundle\Templating\Helper\StopwatchHelper; - -/** - * @group legacy - */ -class StopwatchHelperTest extends TestCase -{ - public function testDevEnvironment() - { - $stopwatch = $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')->getMock(); - $stopwatch->expects($this->once()) - ->method('start') - ->with('foo'); - - $helper = new StopwatchHelper($stopwatch); - $helper->start('foo'); - } - - public function testProdEnvironment() - { - $helper = new StopwatchHelper(null); - $helper->start('foo'); - - // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above - // can be executed without throwing any exceptions - $this->addToAssertionCount(1); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Loader/TemplateLocatorTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Loader/TemplateLocatorTest.php deleted file mode 100644 index 63581e131ed98..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/Loader/TemplateLocatorTest.php +++ /dev/null @@ -1,99 +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\Tests\Templating\Loader; - -use Symfony\Bundle\FrameworkBundle\Templating\Loader\TemplateLocator; -use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; - -/** - * @group legacy - */ -class TemplateLocatorTest extends TestCase -{ - public function testLocateATemplate() - { - $template = new TemplateReference('bundle', 'controller', 'name', 'format', 'engine'); - - $fileLocator = $this->getFileLocator(); - - $fileLocator - ->expects($this->once()) - ->method('locate') - ->with($template->getPath()) - ->willReturn('/path/to/template') - ; - - $locator = new TemplateLocator($fileLocator); - - $this->assertEquals('/path/to/template', $locator->locate($template)); - - // Assert cache is used as $fileLocator->locate should be called only once - $this->assertEquals('/path/to/template', $locator->locate($template)); - } - - public function testLocateATemplateFromCacheDir() - { - $template = new TemplateReference('bundle', 'controller', 'name', 'format', 'engine'); - - $fileLocator = $this->getFileLocator(); - - $locator = new TemplateLocator($fileLocator, __DIR__.'/../../Fixtures'); - - $this->assertEquals(realpath(__DIR__.'/../../Fixtures/Resources/views/this.is.a.template.format.engine'), $locator->locate($template)); - } - - public function testThrowsExceptionWhenTemplateNotFound() - { - $template = new TemplateReference('bundle', 'controller', 'name', 'format', 'engine'); - - $fileLocator = $this->getFileLocator(); - - $errorMessage = 'FileLocator exception message'; - - $fileLocator - ->expects($this->once()) - ->method('locate') - ->willThrowException(new \InvalidArgumentException($errorMessage)) - ; - - $locator = new TemplateLocator($fileLocator); - - try { - $locator->locate($template); - $this->fail('->locate() should throw an exception when the file is not found.'); - } catch (\InvalidArgumentException $e) { - $this->assertStringContainsString( - $errorMessage, - $e->getMessage(), - 'TemplateLocator exception should propagate the FileLocator exception message' - ); - } - } - - public function testThrowsAnExceptionWhenTemplateIsNotATemplateReferenceInterface() - { - $this->expectException('InvalidArgumentException'); - $locator = new TemplateLocator($this->getFileLocator()); - $locator->locate('template'); - } - - protected function getFileLocator() - { - return $this - ->getMockBuilder('Symfony\Component\Config\FileLocator') - ->setMethods(['locate']) - ->setConstructorArgs(['/path/to/fallback']) - ->getMock() - ; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/PhpEngineTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/PhpEngineTest.php deleted file mode 100644 index 77cbeb59980b4..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/PhpEngineTest.php +++ /dev/null @@ -1,75 +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\Tests\Templating; - -use Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables; -use Symfony\Bundle\FrameworkBundle\Templating\PhpEngine; -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; -use Symfony\Component\DependencyInjection\Container; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\RequestStack; -use Symfony\Component\HttpFoundation\Session\Session; -use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage; -use Symfony\Component\Templating\TemplateNameParser; - -/** - * @group legacy - */ -class PhpEngineTest extends TestCase -{ - public function testEvaluateAddsAppGlobal() - { - $container = $this->getContainer(); - $loader = $this->getMockForAbstractClass('Symfony\Component\Templating\Loader\Loader'); - $engine = new PhpEngine(new TemplateNameParser(), $container, $loader, $app = new GlobalVariables($container)); - $globals = $engine->getGlobals(); - $this->assertSame($app, $globals['app']); - } - - public function testEvaluateWithoutAvailableRequest() - { - $container = new Container(); - $loader = $this->getMockForAbstractClass('Symfony\Component\Templating\Loader\Loader'); - $engine = new PhpEngine(new TemplateNameParser(), $container, $loader, new GlobalVariables($container)); - - $this->assertFalse($container->has('request_stack')); - $globals = $engine->getGlobals(); - $this->assertEmpty($globals['app']->getRequest()); - } - - public function testGetInvalidHelper() - { - $this->expectException('InvalidArgumentException'); - $container = $this->getContainer(); - $loader = $this->getMockForAbstractClass('Symfony\Component\Templating\Loader\Loader'); - $engine = new PhpEngine(new TemplateNameParser(), $container, $loader); - - $engine->get('non-existing-helper'); - } - - /** - * Creates a Container with a Session-containing Request service. - */ - protected function getContainer(): Container - { - $container = new Container(); - $session = new Session(new MockArraySessionStorage()); - $request = new Request(); - $stack = new RequestStack(); - $stack->push($request); - - $request->setSession($session); - $container->set('request_stack', $stack); - - return $container; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateFilenameParserTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateFilenameParserTest.php deleted file mode 100644 index 58e671ddf358b..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateFilenameParserTest.php +++ /dev/null @@ -1,59 +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\Tests\Templating; - -use Symfony\Bundle\FrameworkBundle\Templating\TemplateFilenameParser; -use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; - -/** - * @group legacy - */ -class TemplateFilenameParserTest extends TestCase -{ - protected $parser; - - protected function setUp(): void - { - $this->parser = new TemplateFilenameParser(); - } - - protected function tearDown(): void - { - $this->parser = null; - } - - /** - * @dataProvider getFilenameToTemplateProvider - */ - public function testParseFromFilename($file, $ref) - { - $template = $this->parser->parse($file); - - if (false === $ref) { - $this->assertFalse($template); - } else { - $this->assertEquals($template->getLogicalName(), $ref->getLogicalName()); - } - } - - public function getFilenameToTemplateProvider() - { - return [ - ['/path/to/section/name.format.engine', new TemplateReference('', '/path/to/section', 'name', 'format', 'engine')], - ['\\path\\to\\section\\name.format.engine', new TemplateReference('', '/path/to/section', 'name', 'format', 'engine')], - ['name.format.engine', new TemplateReference('', '', 'name', 'format', 'engine')], - ['name.format', false], - ['name', false], - ]; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php deleted file mode 100644 index d3e8272d22c6f..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateNameParserTest.php +++ /dev/null @@ -1,85 +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\Tests\Templating; - -use Symfony\Bundle\FrameworkBundle\Templating\TemplateNameParser; -use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; -use Symfony\Component\Templating\TemplateReference as BaseTemplateReference; - -/** - * @group legacy - */ -class TemplateNameParserTest extends TestCase -{ - protected $parser; - - protected function setUp(): void - { - $kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\KernelInterface')->getMock(); - $kernel - ->expects($this->any()) - ->method('getBundle') - ->willReturnCallback(function ($bundle) { - if (\in_array($bundle, ['SensioFooBundle', 'SensioCmsFooBundle', 'FooBundle'])) { - return true; - } - - throw new \InvalidArgumentException(); - }) - ; - $this->parser = new TemplateNameParser($kernel); - } - - protected function tearDown(): void - { - $this->parser = null; - } - - /** - * @dataProvider parseProvider - */ - public function testParse($name, $logicalName, $path, $ref) - { - $template = $this->parser->parse($name); - - $this->assertSame($ref->getLogicalName(), $template->getLogicalName()); - $this->assertSame($logicalName, $template->getLogicalName()); - $this->assertSame($path, $template->getPath()); - } - - public function parseProvider() - { - return [ - ['FooBundle:Post:index.html.php', 'FooBundle:Post:index.html.php', '@FooBundle/Resources/views/Post/index.html.php', new TemplateReference('FooBundle', 'Post', 'index', 'html', 'php')], - ['FooBundle:Post:index.html.twig', 'FooBundle:Post:index.html.twig', '@FooBundle/Resources/views/Post/index.html.twig', new TemplateReference('FooBundle', 'Post', 'index', 'html', 'twig')], - ['FooBundle:Post:index.xml.php', 'FooBundle:Post:index.xml.php', '@FooBundle/Resources/views/Post/index.xml.php', new TemplateReference('FooBundle', 'Post', 'index', 'xml', 'php')], - ['SensioFooBundle:Post:index.html.php', 'SensioFooBundle:Post:index.html.php', '@SensioFooBundle/Resources/views/Post/index.html.php', new TemplateReference('SensioFooBundle', 'Post', 'index', 'html', 'php')], - ['SensioCmsFooBundle:Post:index.html.php', 'SensioCmsFooBundle:Post:index.html.php', '@SensioCmsFooBundle/Resources/views/Post/index.html.php', new TemplateReference('SensioCmsFooBundle', 'Post', 'index', 'html', 'php')], - [':Post:index.html.php', ':Post:index.html.php', 'views/Post/index.html.php', new TemplateReference('', 'Post', 'index', 'html', 'php')], - ['::index.html.php', '::index.html.php', 'views/index.html.php', new TemplateReference('', '', 'index', 'html', 'php')], - ['index.html.php', '::index.html.php', 'views/index.html.php', new TemplateReference('', '', 'index', 'html', 'php')], - ['FooBundle:Post:foo.bar.index.html.php', 'FooBundle:Post:foo.bar.index.html.php', '@FooBundle/Resources/views/Post/foo.bar.index.html.php', new TemplateReference('FooBundle', 'Post', 'foo.bar.index', 'html', 'php')], - ['@FooBundle/Resources/views/layout.html.twig', '@FooBundle/Resources/views/layout.html.twig', '@FooBundle/Resources/views/layout.html.twig', new BaseTemplateReference('@FooBundle/Resources/views/layout.html.twig', 'twig')], - ['@FooBundle/Foo/layout.html.twig', '@FooBundle/Foo/layout.html.twig', '@FooBundle/Foo/layout.html.twig', new BaseTemplateReference('@FooBundle/Foo/layout.html.twig', 'twig')], - ['name.twig', 'name.twig', 'name.twig', new BaseTemplateReference('name.twig', 'twig')], - ['name', 'name', 'name', new BaseTemplateReference('name')], - ['default/index.html.php', '::default/index.html.php', 'views/default/index.html.php', new TemplateReference(null, null, 'default/index', 'html', 'php')], - ]; - } - - public function testParseValidNameWithNotFoundBundle() - { - $this->expectException('InvalidArgumentException'); - $this->parser->parse('BarBundle:Post:index.html.php'); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateReferenceTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateReferenceTest.php deleted file mode 100644 index 179c3b6da0dbd..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateReferenceTest.php +++ /dev/null @@ -1,31 +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\Tests\Templating; - -use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; - -/** - * @group legacy - */ -class TemplateReferenceTest extends TestCase -{ - public function testGetPathWorksWithNamespacedControllers() - { - $reference = new TemplateReference('AcmeBlogBundle', 'Admin\Post', 'index', 'html', 'twig'); - - $this->assertSame( - '@AcmeBlogBundle/Resources/views/Admin/Post/index.html.twig', - $reference->getPath() - ); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php deleted file mode 100644 index 899740169f207..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TemplateTest.php +++ /dev/null @@ -1,39 +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\Tests\Templating; - -use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference; -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; - -/** - * @group legacy - */ -class TemplateTest extends TestCase -{ - /** - * @dataProvider getTemplateToPathProvider - */ - public function testGetPathForTemplate($template, $path) - { - $this->assertSame($template->getPath(), $path); - } - - public function getTemplateToPathProvider() - { - return [ - [new TemplateReference('FooBundle', 'Post', 'index', 'html', 'php'), '@FooBundle/Resources/views/Post/index.html.php'], - [new TemplateReference('FooBundle', '', 'index', 'html', 'twig'), '@FooBundle/Resources/views/index.html.twig'], - [new TemplateReference('', 'Post', 'index', 'html', 'php'), 'views/Post/index.html.php'], - [new TemplateReference('', '', 'index', 'html', 'php'), 'views/index.html.php'], - ]; - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TimedPhpEngineTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TimedPhpEngineTest.php deleted file mode 100644 index 2e9ca7e650c87..0000000000000 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Templating/TimedPhpEngineTest.php +++ /dev/null @@ -1,104 +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\Tests\Templating; - -use Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables; -use Symfony\Bundle\FrameworkBundle\Templating\TimedPhpEngine; -use Symfony\Bundle\FrameworkBundle\Tests\TestCase; -use Symfony\Component\DependencyInjection\Container; -use Symfony\Component\Stopwatch\Stopwatch; -use Symfony\Component\Stopwatch\StopwatchEvent; -use Symfony\Component\Templating\Loader\Loader; -use Symfony\Component\Templating\Storage\StringStorage; -use Symfony\Component\Templating\TemplateNameParserInterface; - -/** - * @group legacy - */ -class TimedPhpEngineTest extends TestCase -{ - public function testThatRenderLogsTime() - { - $container = $this->getContainer(); - $templateNameParser = $this->getTemplateNameParser(); - $globalVariables = $this->getGlobalVariables(); - $loader = $this->getLoader($this->getStorage()); - - $stopwatch = $this->getStopwatch(); - $stopwatchEvent = $this->getStopwatchEvent(); - - $stopwatch->expects($this->once()) - ->method('start') - ->with('template.php (index.php)', 'template') - ->willReturn($stopwatchEvent); - - $stopwatchEvent->expects($this->once())->method('stop'); - - $engine = new TimedPhpEngine($templateNameParser, $container, $loader, $stopwatch, $globalVariables); - $engine->render('index.php'); - } - - private function getContainer(): Container - { - return $this->getMockBuilder('Symfony\Component\DependencyInjection\Container')->getMock(); - } - - private function getTemplateNameParser(): TemplateNameParserInterface - { - $templateReference = $this->getMockBuilder('Symfony\Component\Templating\TemplateReferenceInterface')->getMock(); - $templateNameParser = $this->getMockBuilder('Symfony\Component\Templating\TemplateNameParserInterface')->getMock(); - $templateNameParser->expects($this->any()) - ->method('parse') - ->willReturn($templateReference); - - return $templateNameParser; - } - - private function getGlobalVariables(): GlobalVariables - { - return $this->getMockBuilder('Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables') - ->disableOriginalConstructor() - ->getMock(); - } - - private function getStorage(): StringStorage - { - return $this->getMockBuilder('Symfony\Component\Templating\Storage\StringStorage') - ->disableOriginalConstructor() - ->getMockForAbstractClass(); - } - - /** - * @param StringStorage $storage - */ - private function getLoader($storage): Loader - { - $loader = $this->getMockForAbstractClass('Symfony\Component\Templating\Loader\Loader'); - $loader->expects($this->once()) - ->method('load') - ->willReturn($storage); - - return $loader; - } - - private function getStopwatchEvent(): StopwatchEvent - { - return $this->getMockBuilder('Symfony\Component\Stopwatch\StopwatchEvent') - ->disableOriginalConstructor() - ->getMock(); - } - - private function getStopwatch(): Stopwatch - { - return $this->getMockBuilder('Symfony\Component\Stopwatch\Stopwatch')->getMock(); - } -} diff --git a/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php b/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php index 52e3ef05e4f7c..fd7fe7158bf78 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php +++ b/src/Symfony/Bundle/FrameworkBundle/Tests/Translation/TranslatorTest.php @@ -63,19 +63,6 @@ public function testTransWithoutCaching() $this->assertEquals('foobarbax (sr@latin)', $translator->trans('foobarbax')); } - /** - * @group legacy - */ - public function testTransChoiceWithoutCaching() - { - $translator = $this->getTranslator($this->getLoader()); - $translator->setLocale('fr'); - $translator->setFallbackLocales(['en', 'es', 'pt-PT', 'pt_BR', 'fr.UTF-8', 'sr@latin']); - - $this->assertEquals('choice 0 (EN)', $translator->transChoice('choice', 0)); - $this->assertEquals('other choice 1 (PT-BR)', $translator->transChoice('other choice', 1)); - } - public function testTransWithCaching() { // prime the cache @@ -110,31 +97,6 @@ public function testTransWithCaching() $this->assertEquals('foobarbax (sr@latin)', $translator->trans('foobarbax')); } - /** - * @group legacy - */ - public function testTransChoiceWithCaching() - { - // prime the cache - $translator = $this->getTranslator($this->getLoader(), ['cache_dir' => $this->tmpDir]); - $translator->setLocale('fr'); - $translator->setFallbackLocales(['en', 'es', 'pt-PT', 'pt_BR', 'fr.UTF-8', 'sr@latin']); - - $this->assertEquals('choice 0 (EN)', $translator->transChoice('choice', 0)); - $this->assertEquals('other choice 1 (PT-BR)', $translator->transChoice('other choice', 1)); - - // do it another time as the cache is primed now - $loader = $this->getMockBuilder('Symfony\Component\Translation\Loader\LoaderInterface')->getMock(); - $loader->expects($this->never())->method('load'); - - $translator = $this->getTranslator($loader, ['cache_dir' => $this->tmpDir]); - $translator->setLocale('fr'); - $translator->setFallbackLocales(['en', 'es', 'pt-PT', 'pt_BR', 'fr.UTF-8', 'sr@latin']); - - $this->assertEquals('choice 0 (EN)', $translator->transChoice('choice', 0)); - $this->assertEquals('other choice 1 (PT-BR)', $translator->transChoice('other choice', 1)); - } - public function testTransWithCachingWithInvalidLocale() { $this->expectException('InvalidArgumentException'); diff --git a/src/Symfony/Bundle/FrameworkBundle/Translation/Translator.php b/src/Symfony/Bundle/FrameworkBundle/Translation/Translator.php index ec6a5febaaa74..da4384dadbf99 100644 --- a/src/Symfony/Bundle/FrameworkBundle/Translation/Translator.php +++ b/src/Symfony/Bundle/FrameworkBundle/Translation/Translator.php @@ -90,7 +90,7 @@ public function __construct(ContainerInterface $container, MessageFormatterInter /** * {@inheritdoc} */ - public function warmUp($cacheDir) + public function warmUp(string $cacheDir) { // skip warmUp when translator doesn't use cache if (null === $this->options['cache_dir']) { @@ -108,7 +108,7 @@ public function warmUp($cacheDir) } } - public function addResource($format, $resource, $locale, $domain = null) + public function addResource(string $format, $resource, string $locale, string $domain = null) { if ($this->resourceFiles) { $this->addResourceFiles(); @@ -119,7 +119,7 @@ public function addResource($format, $resource, $locale, $domain = null) /** * {@inheritdoc} */ - protected function initializeCatalogue($locale) + protected function initializeCatalogue(string $locale) { $this->initialize(); parent::initializeCatalogue($locale); diff --git a/src/Symfony/Bundle/FrameworkBundle/composer.json b/src/Symfony/Bundle/FrameworkBundle/composer.json index 7022e25a21b88..c71a6025029ac 100644 --- a/src/Symfony/Bundle/FrameworkBundle/composer.json +++ b/src/Symfony/Bundle/FrameworkBundle/composer.json @@ -16,77 +16,76 @@ } ], "require": { - "php": "^7.1.3", + "php": "^7.2.5", "ext-xml": "*", "symfony/cache": "^4.4|^5.0", - "symfony/config": "^4.3.4|^5.0", - "symfony/dependency-injection": "^4.4|^5.0", + "symfony/config": "^5.0", + "symfony/dependency-injection": "^5.0", "symfony/http-foundation": "^4.4|^5.0", - "symfony/http-kernel": "^4.4", + "symfony/http-kernel": "^5.0", "symfony/polyfill-mbstring": "~1.0", - "symfony/filesystem": "^3.4|^4.0|^5.0", - "symfony/finder": "^3.4|^4.0|^5.0", - "symfony/routing": "^4.4|^5.0" + "symfony/filesystem": "^4.4|^5.0", + "symfony/finder": "^4.4|^5.0", + "symfony/routing": "^5.1" }, "require-dev": { "doctrine/annotations": "~1.7", "doctrine/cache": "~1.0", - "paragonie/sodium_compat": "^1.8", - "symfony/asset": "^3.4|^4.0|^5.0", - "symfony/browser-kit": "^4.3|^5.0", - "symfony/console": "^4.3.4|^5.0", - "symfony/css-selector": "^3.4|^4.0|^5.0", - "symfony/dom-crawler": "^4.3|^5.0", - "symfony/dotenv": "^4.3.6|^5.0", + "symfony/asset": "^4.4|^5.0", + "symfony/browser-kit": "^4.4|^5.0", + "symfony/console": "^4.4|^5.0", + "symfony/css-selector": "^4.4|^5.0", + "symfony/dom-crawler": "^4.4|^5.0", + "symfony/dotenv": "^4.4|^5.0", "symfony/polyfill-intl-icu": "~1.0", - "symfony/form": "^4.3.4|^5.0", - "symfony/expression-language": "^3.4|^4.0|^5.0", + "symfony/form": "^4.4|^5.0", + "symfony/expression-language": "^4.4|^5.0", "symfony/http-client": "^4.4|^5.0", "symfony/lock": "^4.4|^5.0", "symfony/mailer": "^4.4|^5.0", "symfony/messenger": "^4.4|^5.0", "symfony/mime": "^4.4|^5.0", - "symfony/process": "^3.4|^4.0|^5.0", - "symfony/security-csrf": "^3.4|^4.0|^5.0", - "symfony/security-http": "^3.4|^4.0|^5.0", + "symfony/process": "^4.4|^5.0", + "symfony/security-csrf": "^4.4|^5.0", + "symfony/security-http": "^4.4|^5.0", "symfony/serializer": "^4.4|^5.0", - "symfony/stopwatch": "^3.4|^4.0|^5.0", - "symfony/translation": "^4.4|^5.0", - "symfony/templating": "^3.4|^4.0|^5.0", + "symfony/stopwatch": "^4.4|^5.0", + "symfony/string": "^5.0", + "symfony/translation": "^5.0", "symfony/twig-bundle": "^4.4|^5.0", "symfony/validator": "^4.4|^5.0", - "symfony/workflow": "^4.3.6|^5.0", - "symfony/yaml": "^3.4|^4.0|^5.0", - "symfony/property-info": "^3.4|^4.0|^5.0", + "symfony/workflow": "^4.4|^5.0", + "symfony/yaml": "^4.4|^5.0", + "symfony/property-info": "^4.4|^5.0", "symfony/web-link": "^4.4|^5.0", "phpdocumentor/reflection-docblock": "^3.0|^4.0", - "twig/twig": "^1.41|^2.10|^3.0" + "paragonie/sodium_compat": "^1.8", + "twig/twig": "^2.10|^3.0" }, "conflict": { "phpdocumentor/reflection-docblock": "<3.0", "phpdocumentor/type-resolver": "<0.2.1", - "phpunit/phpunit": "<4.8.35|<5.4.3,>=5.0", - "symfony/asset": "<3.4", - "symfony/browser-kit": "<4.3", - "symfony/console": "<4.3", - "symfony/dotenv": "<4.3.6", - "symfony/dom-crawler": "<4.3", + "phpunit/phpunit": "<5.4.3", + "symfony/asset": "<4.4", + "symfony/browser-kit": "<4.4", + "symfony/console": "<4.4", + "symfony/dotenv": "<4.4", + "symfony/dom-crawler": "<4.4", "symfony/http-client": "<4.4", - "symfony/form": "<4.3", + "symfony/form": "<4.4", "symfony/lock": "<4.4", "symfony/mailer": "<4.4", "symfony/messenger": "<4.4", "symfony/mime": "<4.4", - "symfony/property-info": "<3.4", - "symfony/security-bundle": "<4.4", + "symfony/property-info": "<4.4", "symfony/serializer": "<4.4", - "symfony/stopwatch": "<3.4", - "symfony/translation": "<4.4", - "symfony/twig-bridge": "<4.1.1", + "symfony/stopwatch": "<4.4", + "symfony/translation": "<5.0", + "symfony/twig-bridge": "<4.4", "symfony/twig-bundle": "<4.4", "symfony/validator": "<4.4", "symfony/web-profiler-bundle": "<4.4", - "symfony/workflow": "<4.3.6" + "symfony/workflow": "<4.4" }, "suggest": { "ext-apcu": "For best performance of the system caches", @@ -107,7 +106,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.1-dev" } } } diff --git a/src/Symfony/Bundle/SecurityBundle/CHANGELOG.md b/src/Symfony/Bundle/SecurityBundle/CHANGELOG.md index 5a18e1f7b05ee..7f0fe56f17665 100644 --- a/src/Symfony/Bundle/SecurityBundle/CHANGELOG.md +++ b/src/Symfony/Bundle/SecurityBundle/CHANGELOG.md @@ -1,6 +1,22 @@ CHANGELOG ========= +5.0.0 +----- + + * The `switch_user.stateless` firewall option has been removed. + * Removed the ability to configure encoders using `argon2i` or `bcrypt` as algorithm, use `auto` instead + * The `simple_form` and `simple_preauth` authentication listeners have been removed, + use Guard instead. + * The `SimpleFormFactory` and `SimplePreAuthenticationFactory` classes have been removed, + use Guard instead. + * Removed `LogoutUrlHelper` and `SecurityHelper` templating helpers, use Twig instead + * Removed the `logout_on_user_change` firewall option + * Removed the `threads` encoder option + * Removed the `security.authentication.trust_resolver.anonymous_class` parameter + * Removed the `security.authentication.trust_resolver.rememberme_class` parameter + * Removed the `security.user.provider.in_memory.user` service. + 4.4.0 ----- diff --git a/src/Symfony/Bundle/SecurityBundle/CacheWarmer/ExpressionCacheWarmer.php b/src/Symfony/Bundle/SecurityBundle/CacheWarmer/ExpressionCacheWarmer.php index 938b28dcb637b..c3126ae7dbb17 100644 --- a/src/Symfony/Bundle/SecurityBundle/CacheWarmer/ExpressionCacheWarmer.php +++ b/src/Symfony/Bundle/SecurityBundle/CacheWarmer/ExpressionCacheWarmer.php @@ -34,7 +34,7 @@ public function isOptional() return true; } - public function warmUp($cacheDir) + public function warmUp(string $cacheDir) { foreach ($this->expressions as $expression) { $this->expressionLanguage->parse($expression, ['token', 'user', 'object', 'subject', 'roles', 'request', 'trust_resolver']); diff --git a/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php b/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php index 4fb0b3f5f57d4..9bd7c005757bb 100644 --- a/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php +++ b/src/Symfony/Bundle/SecurityBundle/DataCollector/SecurityDataCollector.php @@ -23,9 +23,7 @@ use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface; use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager; use Symfony\Component\Security\Core\Authorization\Voter\TraceableVoter; -use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\Role\RoleHierarchyInterface; -use Symfony\Component\Security\Core\Role\SwitchUserRole; use Symfony\Component\Security\Http\Firewall\SwitchUserListener; use Symfony\Component\Security\Http\FirewallMapInterface; use Symfony\Component\Security\Http\Logout\LogoutUrlGenerator; @@ -35,7 +33,7 @@ /** * @author Fabien Potencier * - * @final since Symfony 4.4 + * @final */ class SecurityDataCollector extends DataCollector implements LateDataCollectorInterface { @@ -60,10 +58,8 @@ public function __construct(TokenStorageInterface $tokenStorage = null, RoleHier /** * {@inheritdoc} - * - * @param \Throwable|null $exception */ - public function collect(Request $request, Response $response/*, \Throwable $exception = null*/) + public function collect(Request $request, Response $response, \Throwable $exception = null) { if (null === $this->tokenStorage) { $this->data = [ @@ -97,33 +93,15 @@ public function collect(Request $request, Response $response/*, \Throwable $exce ]; } else { $inheritedRoles = []; - - if (method_exists($token, 'getRoleNames')) { - $assignedRoles = $token->getRoleNames(); - } else { - $assignedRoles = array_map(function (Role $role) { return $role->getRole(); }, $token->getRoles(false)); - } + $assignedRoles = $token->getRoleNames(); $impersonatorUser = null; if ($token instanceof SwitchUserToken) { $impersonatorUser = $token->getOriginalToken()->getUsername(); - } else { - foreach ($token->getRoles(false) as $role) { - if ($role instanceof SwitchUserRole) { - $impersonatorUser = $role->getSource()->getUsername(); - break; - } - } } if (null !== $this->roleHierarchy) { - if (method_exists($this->roleHierarchy, 'getReachableRoleNames')) { - $allRoles = $this->roleHierarchy->getReachableRoleNames($assignedRoles); - } else { - $allRoles = array_map(function (Role $role) { return (string) $role; }, $this->roleHierarchy->getReachableRoles($token->getRoles(false))); - } - - foreach ($allRoles as $role) { + foreach ($this->roleHierarchy->getReachableRoleNames($assignedRoles) as $role) { if (!\in_array($role, $assignedRoles, true)) { $inheritedRoles[] = $role; } diff --git a/src/Symfony/Bundle/SecurityBundle/Debug/WrappedListener.php b/src/Symfony/Bundle/SecurityBundle/Debug/WrappedListener.php index 36b01fda12fbd..6cdb04773c51a 100644 --- a/src/Symfony/Bundle/SecurityBundle/Debug/WrappedListener.php +++ b/src/Symfony/Bundle/SecurityBundle/Debug/WrappedListener.php @@ -12,8 +12,6 @@ namespace Symfony\Bundle\SecurityBundle\Debug; use Symfony\Component\HttpKernel\Event\RequestEvent; -use Symfony\Component\Security\Http\Firewall\LegacyListenerTrait; -use Symfony\Component\Security\Http\Firewall\ListenerInterface; use Symfony\Component\VarDumper\Caster\ClassStub; /** @@ -21,38 +19,25 @@ * * @author Robin Chalas * - * @internal since Symfony 4.3 + * @internal */ -final class WrappedListener implements ListenerInterface +final class WrappedListener { - use LegacyListenerTrait; - private $response; private $listener; private $time; private $stub; private static $hasVarDumper; - /** - * @param callable $listener - */ - public function __construct($listener) + public function __construct(callable $listener) { $this->listener = $listener; } - /** - * {@inheritdoc} - */ public function __invoke(RequestEvent $event) { $startTime = microtime(true); - if (\is_callable($this->listener)) { - ($this->listener)($event); - } else { - @trigger_error(sprintf('Calling the "%s::handle()" method from the firewall is deprecated since Symfony 4.3, implement "__invoke()" instead.', \get_class($this->listener)), E_USER_DEPRECATED); - $this->listener->handle($event); - } + ($this->listener)($event); $this->time = microtime(true) - $startTime; $this->response = $event->getResponse(); } @@ -65,7 +50,7 @@ public function __call(string $method, array $arguments) return $this->listener->{$method}(...$arguments); } - public function getWrappedListener() + public function getWrappedListener(): callable { return $this->listener; } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php index 58ea0f3fe4778..ba55fe195c76b 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/MainConfiguration.php @@ -12,8 +12,6 @@ namespace Symfony\Bundle\SecurityBundle\DependencyInjection; use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AbstractFactory; -use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SimpleFormFactory; -use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SimplePreAuthenticationFactory; use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; @@ -198,11 +196,6 @@ private function addFirewallsSection(ArrayNodeDefinition $rootNode, array $facto ->scalarNode('provider')->end() ->booleanNode('stateless')->defaultFalse()->end() ->scalarNode('context')->cannotBeEmpty()->end() - ->booleanNode('logout_on_user_change') - ->defaultTrue() - ->info('When true, it will trigger a logout for the user if something has changed. Note: No-Op option since 4.0. Will always be true.') - ->setDeprecated('The "%path%.%node%" configuration key has been deprecated in Symfony 4.1.') - ->end() ->arrayNode('logout') ->treatTrueLike([]) ->canBeUnset() @@ -223,22 +216,6 @@ private function addFirewallsSection(ArrayNodeDefinition $rootNode, array $facto ->ifTrue(function ($v) { return \is_array($v) && \is_int(key($v)); }) ->then(function ($v) { return array_map(function ($v) { return ['name' => $v]; }, $v); }) ->end() - ->beforeNormalization() - ->ifArray()->then(function ($v) { - foreach ($v as $originalName => $cookieConfig) { - if (false !== strpos($originalName, '-')) { - $normalizedName = str_replace('-', '_', $originalName); - @trigger_error(sprintf('Normalization of cookie names is deprecated since Symfony 4.3. Starting from Symfony 5.0, the "%s" cookie configured in "logout.delete_cookies" will delete the "%s" cookie instead of the "%s" cookie.', $originalName, $originalName, $normalizedName), E_USER_DEPRECATED); - - // normalize cookie names manually for BC reasons. Remove it in Symfony 5.0. - $v[$normalizedName] = $cookieConfig; - unset($v[$originalName]); - } - } - - return $v; - }) - ->end() ->useAttributeAsKey('name') ->prototype('array') ->children() @@ -261,10 +238,6 @@ private function addFirewallsSection(ArrayNodeDefinition $rootNode, array $facto ->scalarNode('provider')->end() ->scalarNode('parameter')->defaultValue('_switch_user')->end() ->scalarNode('role')->defaultValue('ROLE_ALLOWED_TO_SWITCH')->end() - ->booleanNode('stateless') - ->setDeprecated('The "%path%.%node%" configuration key has been deprecated in Symfony 4.1.') - ->defaultValue(false) - ->end() ->end() ->end() ; @@ -277,10 +250,6 @@ private function addFirewallsSection(ArrayNodeDefinition $rootNode, array $facto ->canBeUnset() ; - if ($factory instanceof SimplePreAuthenticationFactory || $factory instanceof SimpleFormFactory) { - $factoryNode->setDeprecated(sprintf('The "%s" security listener is deprecated Symfony 4.2, use Guard instead.', $name)); - } - if ($factory instanceof AbstractFactory) { $abstractFactoryKeys[] = $name; } @@ -410,10 +379,6 @@ private function addEncodersSection(ArrayNodeDefinition $rootNode) ->end() ->scalarNode('memory_cost')->defaultNull()->end() ->scalarNode('time_cost')->defaultNull()->end() - ->scalarNode('threads') - ->defaultNull() - ->setDeprecated('The "%path%.%node%" configuration key has no effect since Symfony 4.3 and will be removed in 5.0.') - ->end() ->scalarNode('id')->end() ->end() ->end() diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php index 79ef873ec2ad2..b523467f230b2 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/AbstractFactory.php @@ -47,7 +47,7 @@ abstract class AbstractFactory implements SecurityFactoryInterface 'failure_path_parameter' => '_failure_path', ]; - public function create(ContainerBuilder $container, $id, $config, $userProviderId, $defaultEntryPointId) + public function create(ContainerBuilder $container, string $id, array $config, string $userProviderId, ?string $defaultEntryPointId) { // authentication provider $authProviderId = $this->createAuthProvider($container, $id, $config, $userProviderId); @@ -98,13 +98,9 @@ final public function addOption(string $name, $default = null) * Subclasses must return the id of a service which implements the * AuthenticationProviderInterface. * - * @param string $id The unique id of the firewall - * @param array $config The options array for this listener - * @param string $userProviderId The id of the user provider - * * @return string never null, the id of the authentication provider */ - abstract protected function createAuthProvider(ContainerBuilder $container, $id, $config, $userProviderId); + abstract protected function createAuthProvider(ContainerBuilder $container, string $id, array $config, string $userProviderId); /** * Subclasses must return the id of the abstract listener template. @@ -127,14 +123,9 @@ abstract protected function getListenerId(); * Subclasses may create an entry point of their as they see fit. The * default implementation does not change the default entry point. * - * @param ContainerBuilder $container - * @param string $id - * @param array $config - * @param string|null $defaultEntryPointId - * * @return string|null the entry point id */ - protected function createEntryPoint($container, $id, $config, $defaultEntryPointId) + protected function createEntryPoint(ContainerBuilder $container, string $id, array $config, ?string $defaultEntryPointId) { return $defaultEntryPointId; } @@ -145,12 +136,12 @@ protected function createEntryPoint($container, $id, $config, $defaultEntryPoint * * @return bool Whether a possibly configured RememberMeServices should be set for this listener */ - protected function isRememberMeAware($config) + protected function isRememberMeAware(array $config) { return $config['remember_me']; } - protected function createListener($container, $id, $config, $userProvider) + protected function createListener(ContainerBuilder $container, string $id, array $config, string $userProvider) { $listenerId = $this->getListenerId(); $listener = new ChildDefinition($listenerId); @@ -165,7 +156,7 @@ protected function createListener($container, $id, $config, $userProvider) return $listenerId; } - protected function createAuthenticationSuccessHandler($container, $id, $config) + protected function createAuthenticationSuccessHandler(ContainerBuilder $container, string $id, array $config) { $successHandlerId = $this->getSuccessHandlerId($id); $options = array_intersect_key($config, $this->defaultSuccessHandlerOptions); @@ -184,7 +175,7 @@ protected function createAuthenticationSuccessHandler($container, $id, $config) return $successHandlerId; } - protected function createAuthenticationFailureHandler($container, $id, $config) + protected function createAuthenticationFailureHandler(ContainerBuilder $container, string $id, array $config) { $id = $this->getFailureHandlerId($id); $options = array_intersect_key($config, $this->defaultFailureHandlerOptions); @@ -201,12 +192,12 @@ protected function createAuthenticationFailureHandler($container, $id, $config) return $id; } - protected function getSuccessHandlerId($id) + protected function getSuccessHandlerId(string $id) { return 'security.authentication.success_handler.'.$id.'.'.str_replace('-', '_', $this->getKey()); } - protected function getFailureHandlerId($id) + protected function getFailureHandlerId(string $id) { return 'security.authentication.failure_handler.'.$id.'.'.str_replace('-', '_', $this->getKey()); } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginFactory.php index 24f0b98ae6fbb..af200264061e6 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginFactory.php @@ -59,7 +59,7 @@ protected function getListenerId() return 'security.authentication.listener.form'; } - protected function createAuthProvider(ContainerBuilder $container, $id, $config, $userProviderId) + protected function createAuthProvider(ContainerBuilder $container, string $id, array $config, string $userProviderId) { $provider = 'security.authentication.provider.dao.'.$id; $container @@ -72,7 +72,7 @@ protected function createAuthProvider(ContainerBuilder $container, $id, $config, return $provider; } - protected function createListener($container, $id, $config, $userProvider) + protected function createListener(ContainerBuilder $container, string $id, array $config, string $userProvider) { $listenerId = parent::createListener($container, $id, $config, $userProvider); @@ -84,7 +84,7 @@ protected function createListener($container, $id, $config, $userProvider) return $listenerId; } - protected function createEntryPoint($container, $id, $config, $defaultEntryPoint) + protected function createEntryPoint(ContainerBuilder $container, string $id, array $config, ?string $defaultEntryPoint) { $entryPointId = 'security.authentication.form_entry_point.'.$id; $container diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginLdapFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginLdapFactory.php index d7b53e5cf4c10..b2136c50560fb 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginLdapFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/FormLoginLdapFactory.php @@ -15,6 +15,7 @@ use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\Security\Core\Exception\LogicException; /** * FormLoginLdapFactory creates services for form login ldap authentication. @@ -24,7 +25,7 @@ */ class FormLoginLdapFactory extends FormLoginFactory { - protected function createAuthProvider(ContainerBuilder $container, $id, $config, $userProviderId) + protected function createAuthProvider(ContainerBuilder $container, string $id, array $config, string $userProviderId) { $provider = 'security.authentication.provider.ldap_bind.'.$id; $definition = $container @@ -40,7 +41,7 @@ protected function createAuthProvider(ContainerBuilder $container, $id, $config, if (!empty($config['query_string'])) { if ('' === $config['search_dn'] || '' === $config['search_password']) { - @trigger_error('Using the "query_string" config without using a "search_dn" and a "search_password" is deprecated since Symfony 4.4 and will throw in Symfony 5.0.', E_USER_DEPRECATED); + throw new LogicException('Using the "query_string" config without using a "search_dn" and a "search_password" is not supported.'); } $definition->addMethodCall('setQueryString', [$config['query_string']]); } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/GuardAuthenticationFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/GuardAuthenticationFactory.php index 0946cfeaa49dc..be4adc6edad99 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/GuardAuthenticationFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/GuardAuthenticationFactory.php @@ -55,7 +55,7 @@ public function addConfiguration(NodeDefinition $node) ; } - public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint) + public function create(ContainerBuilder $container, string $id, array $config, string $userProvider, ?string $defaultEntryPoint) { $authenticatorIds = $config['authenticators']; $authenticatorReferences = []; diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicFactory.php index f3b5bc167e64e..f731469520b4a 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicFactory.php @@ -23,7 +23,7 @@ */ class HttpBasicFactory implements SecurityFactoryInterface { - public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint) + public function create(ContainerBuilder $container, string $id, array $config, string $userProvider, ?string $defaultEntryPoint) { $provider = 'security.authentication.provider.dao.'.$id; $container @@ -66,7 +66,7 @@ public function addConfiguration(NodeDefinition $node) ; } - protected function createEntryPoint($container, $id, $config, $defaultEntryPoint) + protected function createEntryPoint(ContainerBuilder $container, string $id, array $config, ?string $defaultEntryPoint) { if (null !== $defaultEntryPoint) { return $defaultEntryPoint; diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicLdapFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicLdapFactory.php index 09933a9db931b..630e0b75b73f2 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicLdapFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/HttpBasicLdapFactory.php @@ -15,6 +15,7 @@ use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\Security\Core\Exception\LogicException; /** * HttpBasicFactory creates services for HTTP basic authentication. @@ -25,7 +26,7 @@ */ class HttpBasicLdapFactory extends HttpBasicFactory { - public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint) + public function create(ContainerBuilder $container, string $id, array $config, string $userProvider, ?string $defaultEntryPoint) { $provider = 'security.authentication.provider.ldap_bind.'.$id; $definition = $container @@ -44,7 +45,7 @@ public function create(ContainerBuilder $container, $id, $config, $userProvider, if (!empty($config['query_string'])) { if ('' === $config['search_dn'] || '' === $config['search_password']) { - @trigger_error('Using the "query_string" config without using a "search_dn" and a "search_password" is deprecated since Symfony 4.4 and will throw in Symfony 5.0.', E_USER_DEPRECATED); + throw new LogicException('Using the "query_string" config without using a "search_dn" and a "search_password" is not supported.'); } $definition->addMethodCall('setQueryString', [$config['query_string']]); } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/JsonLoginFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/JsonLoginFactory.php index a660401dbea34..f4b9adee939fc 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/JsonLoginFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/JsonLoginFactory.php @@ -49,7 +49,7 @@ public function getKey() /** * {@inheritdoc} */ - protected function createAuthProvider(ContainerBuilder $container, $id, $config, $userProviderId) + protected function createAuthProvider(ContainerBuilder $container, string $id, array $config, string $userProviderId) { $provider = 'security.authentication.provider.dao.'.$id; $container @@ -81,7 +81,7 @@ protected function isRememberMeAware($config) /** * {@inheritdoc} */ - protected function createListener($container, $id, $config, $userProvider) + protected function createListener(ContainerBuilder $container, string $id, array $config, string $userProvider) { $listenerId = $this->getListenerId(); $listener = new ChildDefinition($listenerId); diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/JsonLoginLdapFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/JsonLoginLdapFactory.php index 95f3f558585ee..6428f61c23cbf 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/JsonLoginLdapFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/JsonLoginLdapFactory.php @@ -15,6 +15,7 @@ use Symfony\Component\DependencyInjection\ChildDefinition; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; +use Symfony\Component\Security\Core\Exception\LogicException; /** * JsonLoginLdapFactory creates services for json login ldap authentication. @@ -26,7 +27,7 @@ public function getKey() return 'json-login-ldap'; } - protected function createAuthProvider(ContainerBuilder $container, $id, $config, $userProviderId) + protected function createAuthProvider(ContainerBuilder $container, string $id, array $config, string $userProviderId) { $provider = 'security.authentication.provider.ldap_bind.'.$id; $definition = $container @@ -42,7 +43,7 @@ protected function createAuthProvider(ContainerBuilder $container, $id, $config, if (!empty($config['query_string'])) { if ('' === $config['search_dn'] || '' === $config['search_password']) { - @trigger_error('Using the "query_string" config without using a "search_dn" and a "search_password" is deprecated since Symfony 4.4 and will throw in Symfony 5.0.', E_USER_DEPRECATED); + throw new LogicException('Using the "query_string" config without using a "search_dn" and a "search_password" is not supported.'); } $definition->addMethodCall('setQueryString', [$config['query_string']]); } diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php index 28103a3522542..3cc260d3cf50c 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RememberMeFactory.php @@ -31,7 +31,7 @@ class RememberMeFactory implements SecurityFactoryInterface 'remember_me_parameter' => '_remember_me', ]; - public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint) + public function create(ContainerBuilder $container, string $id, array $config, ?string $userProvider, ?string $defaultEntryPoint) { // authentication provider $authProviderId = 'security.authentication.provider.rememberme.'.$id; diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RemoteUserFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RemoteUserFactory.php index 176f65b13578a..b37229d886e3f 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RemoteUserFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/RemoteUserFactory.php @@ -24,7 +24,7 @@ */ class RemoteUserFactory implements SecurityFactoryInterface { - public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint) + public function create(ContainerBuilder $container, string $id, array $config, string $userProvider, ?string $defaultEntryPoint) { $providerId = 'security.authentication.provider.pre_authenticated.'.$id; $container diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SecurityFactoryInterface.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SecurityFactoryInterface.php index 533e8d0cfce12..4058d3228b512 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SecurityFactoryInterface.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SecurityFactoryInterface.php @@ -24,17 +24,12 @@ interface SecurityFactoryInterface /** * Configures the container services required to use the authentication listener. * - * @param string $id The unique id of the firewall - * @param array $config The options array for the listener - * @param string $userProvider The service id of the user provider - * @param string|null $defaultEntryPoint - * * @return array containing three values: * - the provider id * - the listener id * - the entry point id */ - public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint); + public function create(ContainerBuilder $container, string $id, array $config, string $userProvider, ?string $defaultEntryPoint); /** * Defines the position at which the provider is called. diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SimpleFormFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SimpleFormFactory.php deleted file mode 100644 index 9ffd624a96d92..0000000000000 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SimpleFormFactory.php +++ /dev/null @@ -1,87 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory; - -use Symfony\Component\Config\Definition\Builder\NodeDefinition; -use Symfony\Component\DependencyInjection\ChildDefinition; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Reference; - -/** - * @author Jordi Boggiano - * - * @deprecated since Symfony 4.2, use Guard instead. - */ -class SimpleFormFactory extends FormLoginFactory -{ - public function __construct(bool $triggerDeprecation = true) - { - parent::__construct(); - - $this->addOption('authenticator', null); - - if ($triggerDeprecation) { - @trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use Guard instead.', __CLASS__), E_USER_DEPRECATED); - } - } - - public function getKey() - { - return 'simple-form'; - } - - public function addConfiguration(NodeDefinition $node) - { - parent::addConfiguration($node); - - $node->children() - ->scalarNode('authenticator')->cannotBeEmpty()->end() - ->end(); - } - - protected function getListenerId() - { - return 'security.authentication.listener.simple_form'; - } - - protected function createAuthProvider(ContainerBuilder $container, $id, $config, $userProviderId) - { - $provider = 'security.authentication.provider.simple_form.'.$id; - $container - ->setDefinition($provider, new ChildDefinition('security.authentication.provider.simple')) - ->replaceArgument(0, new Reference($config['authenticator'])) - ->replaceArgument(1, new Reference($userProviderId)) - ->replaceArgument(2, $id) - ->replaceArgument(3, new Reference('security.user_checker.'.$id)) - ; - - return $provider; - } - - protected function createListener($container, $id, $config, $userProvider) - { - $listenerId = parent::createListener($container, $id, $config, $userProvider); - - $simpleAuthHandlerId = 'security.authentication.simple_success_failure_handler.'.$id; - $simpleAuthHandler = $container->setDefinition($simpleAuthHandlerId, new ChildDefinition('security.authentication.simple_success_failure_handler')); - $simpleAuthHandler->replaceArgument(0, new Reference($config['authenticator'])); - $simpleAuthHandler->replaceArgument(1, new Reference($this->getSuccessHandlerId($id))); - $simpleAuthHandler->replaceArgument(2, new Reference($this->getFailureHandlerId($id))); - - $listener = $container->getDefinition($listenerId); - $listener->replaceArgument(5, new Reference($simpleAuthHandlerId)); - $listener->replaceArgument(6, new Reference($simpleAuthHandlerId)); - $listener->addArgument(new Reference($config['authenticator'])); - - return $listenerId; - } -} diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SimplePreAuthenticationFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SimplePreAuthenticationFactory.php deleted file mode 100644 index 04c5ce16aed02..0000000000000 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/SimplePreAuthenticationFactory.php +++ /dev/null @@ -1,73 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory; - -use Symfony\Component\Config\Definition\Builder\NodeDefinition; -use Symfony\Component\DependencyInjection\ChildDefinition; -use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Reference; - -/** - * @author Jordi Boggiano - * - * @deprecated since Symfony 4.2, use Guard instead. - */ -class SimplePreAuthenticationFactory implements SecurityFactoryInterface -{ - public function __construct(bool $triggerDeprecation = true) - { - if ($triggerDeprecation) { - @trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use Guard instead.', __CLASS__), E_USER_DEPRECATED); - } - } - - public function getPosition() - { - return 'pre_auth'; - } - - public function getKey() - { - return 'simple-preauth'; - } - - public function addConfiguration(NodeDefinition $node) - { - $node - ->children() - ->scalarNode('provider')->end() - ->scalarNode('authenticator')->cannotBeEmpty()->end() - ->end() - ; - } - - public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint) - { - $provider = 'security.authentication.provider.simple_preauth.'.$id; - $container - ->setDefinition($provider, new ChildDefinition('security.authentication.provider.simple')) - ->replaceArgument(0, new Reference($config['authenticator'])) - ->replaceArgument(1, new Reference($userProvider)) - ->replaceArgument(2, $id) - ->replaceArgument(3, new Reference('security.user_checker.'.$id)) - ; - - // listener - $listenerId = 'security.authentication.listener.simple_preauth.'.$id; - $listener = $container->setDefinition($listenerId, new ChildDefinition('security.authentication.listener.simple_preauth')); - $listener->replaceArgument(2, $id); - $listener->replaceArgument(3, new Reference($config['authenticator'])); - $listener->addMethodCall('setSessionAuthenticationStrategy', [new Reference('security.authentication.session_strategy.'.$id)]); - - return [$provider, $listenerId, null]; - } -} diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/X509Factory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/X509Factory.php index 35879ee4956b9..e3ba596d933aa 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/X509Factory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/Factory/X509Factory.php @@ -23,7 +23,7 @@ */ class X509Factory implements SecurityFactoryInterface { - public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint) + public function create(ContainerBuilder $container, string $id, array $config, string $userProvider, ?string $defaultEntryPoint) { $providerId = 'security.authentication.provider.pre_authenticated.'.$id; $container diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/UserProvider/InMemoryFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/UserProvider/InMemoryFactory.php index 1e76601105022..a19a9eb163b3f 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/UserProvider/InMemoryFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/UserProvider/InMemoryFactory.php @@ -24,7 +24,7 @@ */ class InMemoryFactory implements UserProviderFactoryInterface { - public function create(ContainerBuilder $container, $id, $config) + public function create(ContainerBuilder $container, string $id, array $config) { $definition = $container->setDefinition($id, new ChildDefinition('security.user.provider.in_memory')); $defaultPassword = new Parameter('container.build_id'); diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/UserProvider/LdapFactory.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/UserProvider/LdapFactory.php index 33e59bfc70e74..97e7243e992bd 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/UserProvider/LdapFactory.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/UserProvider/LdapFactory.php @@ -24,7 +24,7 @@ */ class LdapFactory implements UserProviderFactoryInterface { - public function create(ContainerBuilder $container, $id, $config) + public function create(ContainerBuilder $container, string $id, array $config) { $container ->setDefinition($id, new ChildDefinition('security.user.provider.ldap')) diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/UserProvider/UserProviderFactoryInterface.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/UserProvider/UserProviderFactoryInterface.php index df250358aa61e..6d9481c59cb4a 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/UserProvider/UserProviderFactoryInterface.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/Security/UserProvider/UserProviderFactoryInterface.php @@ -22,7 +22,7 @@ */ interface UserProviderFactoryInterface { - public function create(ContainerBuilder $container, $id, $config); + public function create(ContainerBuilder $container, string $id, array $config); public function getKey(); diff --git a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php index 480768a6d07fc..9b54e1f9141ef 100644 --- a/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php +++ b/src/Symfony/Bundle/SecurityBundle/DependencyInjection/SecurityExtension.php @@ -32,7 +32,6 @@ use Symfony\Component\Security\Core\Encoder\SodiumPasswordEncoder; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Http\Controller\UserValueResolver; -use Symfony\Component\Templating\Helper\Helper; use Twig\Extension\AbstractExtension; /** @@ -100,10 +99,6 @@ public function load(array $configs, ContainerBuilder $container) $loader->load('security_listeners.xml'); $loader->load('security_rememberme.xml'); - if (class_exists(Helper::class)) { - $loader->load('templating_php.xml'); - } - if (class_exists(AbstractExtension::class)) { $loader->load('templating_twig.xml'); } @@ -693,7 +688,7 @@ private function createSwitchUserListener(ContainerBuilder $container, string $i $listener->replaceArgument(3, $id); $listener->replaceArgument(6, $config['parameter']); $listener->replaceArgument(7, $config['role']); - $listener->replaceArgument(9, $stateless ?: $config['stateless']); + $listener->replaceArgument(9, $stateless); return $switchUserListenerId; } diff --git a/src/Symfony/Bundle/SecurityBundle/EventListener/FirewallListener.php b/src/Symfony/Bundle/SecurityBundle/EventListener/FirewallListener.php index 3dca451d9ab17..778bfcfeff077 100644 --- a/src/Symfony/Bundle/SecurityBundle/EventListener/FirewallListener.php +++ b/src/Symfony/Bundle/SecurityBundle/EventListener/FirewallListener.php @@ -12,13 +12,13 @@ namespace Symfony\Bundle\SecurityBundle\EventListener; use Symfony\Bundle\SecurityBundle\Security\FirewallMap; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\HttpKernel\Event\FinishRequestEvent; -use Symfony\Component\HttpKernel\Event\GetResponseEvent; +use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\Security\Http\Firewall; use Symfony\Component\Security\Http\FirewallMapInterface; use Symfony\Component\Security\Http\Logout\LogoutUrlGenerator; +use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; /** * @author Maxime Steinhausser @@ -30,18 +30,13 @@ class FirewallListener extends Firewall public function __construct(FirewallMapInterface $map, EventDispatcherInterface $dispatcher, LogoutUrlGenerator $logoutUrlGenerator) { - // the type-hint will be updated to the "EventDispatcherInterface" from symfony/contracts in 5.0 - $this->map = $map; $this->logoutUrlGenerator = $logoutUrlGenerator; parent::__construct($map, $dispatcher); } - /** - * @internal - */ - public function configureLogoutUrlGenerator(GetResponseEvent $event) + public function configureLogoutUrlGenerator(RequestEvent $event) { if (!$event->isMasterRequest()) { return; @@ -52,9 +47,6 @@ public function configureLogoutUrlGenerator(GetResponseEvent $event) } } - /** - * @internal since Symfony 4.3 - */ public function onKernelFinishRequest(FinishRequestEvent $event) { if ($event->isMasterRequest()) { diff --git a/src/Symfony/Bundle/SecurityBundle/Resources/config/security.xml b/src/Symfony/Bundle/SecurityBundle/Resources/config/security.xml index 410646d9ba5d6..0408a48077f50 100644 --- a/src/Symfony/Bundle/SecurityBundle/Resources/config/security.xml +++ b/src/Symfony/Bundle/SecurityBundle/Resources/config/security.xml @@ -5,8 +5,6 @@ xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd"> - null - null @@ -56,10 +54,7 @@ - - %security.authentication.trust_resolver.anonymous_class% - %security.authentication.trust_resolver.rememberme_class% - + %security.authentication.session_strategy.strategy% @@ -188,9 +183,6 @@ - - The "%service_id%" service is deprecated since Symfony 4.1. - diff --git a/src/Symfony/Bundle/SecurityBundle/Resources/config/security_listeners.xml b/src/Symfony/Bundle/SecurityBundle/Resources/config/security_listeners.xml index e1a9ce5c038e1..e660ed8b12be5 100644 --- a/src/Symfony/Bundle/SecurityBundle/Resources/config/security_listeners.xml +++ b/src/Symfony/Bundle/SecurityBundle/Resources/config/security_listeners.xml @@ -109,35 +109,6 @@ public="false" abstract="true" /> - - The "%service_id%" service is deprecated since Symfony 4.2. - - - - - - - - - The "%service_id%" service is deprecated since Symfony 4.2. - - - - - - - - - - - - The "%service_id%" service is deprecated since Symfony 4.2. - - @@ -201,14 +172,6 @@ %security.authentication.hide_user_not_found% - - - - - null - The "%service_id%" service is deprecated since Symfony 4.2. - - diff --git a/src/Symfony/Bundle/SecurityBundle/Resources/config/templating_php.xml b/src/Symfony/Bundle/SecurityBundle/Resources/config/templating_php.xml deleted file mode 100644 index b2bafbc60546f..0000000000000 --- a/src/Symfony/Bundle/SecurityBundle/Resources/config/templating_php.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - - - - - The "%service_id%" service is deprecated since Symfony 4.3 and will be removed in 5.0. - - - diff --git a/src/Symfony/Bundle/SecurityBundle/Security/FirewallContext.php b/src/Symfony/Bundle/SecurityBundle/Security/FirewallContext.php index d811faac4bf06..00754e4363cfc 100644 --- a/src/Symfony/Bundle/SecurityBundle/Security/FirewallContext.php +++ b/src/Symfony/Bundle/SecurityBundle/Security/FirewallContext.php @@ -27,22 +27,12 @@ class FirewallContext private $logoutListener; private $config; - /** - * @param LogoutListener|null $logoutListener - */ - public function __construct(iterable $listeners, ExceptionListener $exceptionListener = null, $logoutListener = null, FirewallConfig $config = null) + public function __construct(iterable $listeners, ExceptionListener $exceptionListener = null, LogoutListener $logoutListener = null, FirewallConfig $config = null) { $this->listeners = $listeners; $this->exceptionListener = $exceptionListener; - if ($logoutListener instanceof FirewallConfig) { - $this->config = $logoutListener; - @trigger_error(sprintf('Passing an instance of %s as the 3rd argument to "%s()" is deprecated since Symfony 4.2. Pass a %s instance instead.', FirewallConfig::class, __METHOD__, LogoutListener::class), E_USER_DEPRECATED); - } elseif (null === $logoutListener || $logoutListener instanceof LogoutListener) { - $this->logoutListener = $logoutListener; - $this->config = $config; - } else { - throw new \TypeError(sprintf('Argument 3 passed to %s() must be instance of %s or null, %s given.', __METHOD__, LogoutListener::class, \is_object($logoutListener) ? \get_class($logoutListener) : \gettype($logoutListener))); - } + $this->logoutListener = $logoutListener; + $this->config = $config; } public function getConfig() diff --git a/src/Symfony/Bundle/SecurityBundle/Security/LazyFirewallContext.php b/src/Symfony/Bundle/SecurityBundle/Security/LazyFirewallContext.php index ef9b1e217cd5a..78ee1f275e28c 100644 --- a/src/Symfony/Bundle/SecurityBundle/Security/LazyFirewallContext.php +++ b/src/Symfony/Bundle/SecurityBundle/Security/LazyFirewallContext.php @@ -51,12 +51,7 @@ public function __invoke(RequestEvent $event) $this->tokenStorage->setInitializer(function () use ($event) { $event = new LazyResponseEvent($event); foreach (parent::getListeners() as $listener) { - if (\is_callable($listener)) { - $listener($event); - } else { - @trigger_error(sprintf('Calling the "%s::handle()" method from the firewall is deprecated since Symfony 4.3, implement "__invoke()" instead.', \get_class($listener)), E_USER_DEPRECATED); - $listener->handle($event); - } + $listener($event); } }); diff --git a/src/Symfony/Bundle/SecurityBundle/SecurityBundle.php b/src/Symfony/Bundle/SecurityBundle/SecurityBundle.php index 24cf5569b819b..b3243c83d7daf 100644 --- a/src/Symfony/Bundle/SecurityBundle/SecurityBundle.php +++ b/src/Symfony/Bundle/SecurityBundle/SecurityBundle.php @@ -26,8 +26,6 @@ use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\JsonLoginLdapFactory; use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\RememberMeFactory; use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\RemoteUserFactory; -use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SimpleFormFactory; -use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SimplePreAuthenticationFactory; use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\X509Factory; use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\InMemoryFactory; use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\LdapFactory; @@ -63,8 +61,6 @@ public function build(ContainerBuilder $container) $extension->addSecurityListenerFactory(new RememberMeFactory()); $extension->addSecurityListenerFactory(new X509Factory()); $extension->addSecurityListenerFactory(new RemoteUserFactory()); - $extension->addSecurityListenerFactory(new SimplePreAuthenticationFactory(false)); - $extension->addSecurityListenerFactory(new SimpleFormFactory(false)); $extension->addSecurityListenerFactory(new GuardAuthenticationFactory()); $extension->addSecurityListenerFactory(new AnonymousFactory()); diff --git a/src/Symfony/Bundle/SecurityBundle/SecurityUserValueResolver.php b/src/Symfony/Bundle/SecurityBundle/SecurityUserValueResolver.php deleted file mode 100644 index 25a9244f2fc35..0000000000000 --- a/src/Symfony/Bundle/SecurityBundle/SecurityUserValueResolver.php +++ /dev/null @@ -1,62 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\SecurityBundle; - -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface; -use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface; -use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; -use Symfony\Component\Security\Core\User\UserInterface; -use Symfony\Component\Security\Http\Controller\UserValueResolver; - -@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.1, use "%s" instead.', SecurityUserValueResolver::class, UserValueResolver::class), E_USER_DEPRECATED); - -/** - * Supports the argument type of {@see UserInterface}. - * - * @author Iltar van der Berg - * - * @deprecated since Symfony 4.1, use {@link UserValueResolver} instead - */ -final class SecurityUserValueResolver implements ArgumentValueResolverInterface -{ - private $tokenStorage; - - public function __construct(TokenStorageInterface $tokenStorage) - { - $this->tokenStorage = $tokenStorage; - } - - public function supports(Request $request, ArgumentMetadata $argument): bool - { - // only security user implementations are supported - if (UserInterface::class !== $argument->getType()) { - return false; - } - - $token = $this->tokenStorage->getToken(); - if (!$token instanceof TokenInterface) { - return false; - } - - $user = $token->getUser(); - - // in case it's not an object we cannot do anything with it; E.g. "anon." - return $user instanceof UserInterface; - } - - public function resolve(Request $request, ArgumentMetadata $argument): iterable - { - yield $this->tokenStorage->getToken()->getUser(); - } -} diff --git a/src/Symfony/Bundle/SecurityBundle/Templating/Helper/LogoutUrlHelper.php b/src/Symfony/Bundle/SecurityBundle/Templating/Helper/LogoutUrlHelper.php deleted file mode 100644 index 30ef9c2829028..0000000000000 --- a/src/Symfony/Bundle/SecurityBundle/Templating/Helper/LogoutUrlHelper.php +++ /dev/null @@ -1,66 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\SecurityBundle\Templating\Helper; - -@trigger_error('The '.LogoutUrlHelper::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\Security\Http\Logout\LogoutUrlGenerator; -use Symfony\Component\Templating\Helper\Helper; - -/** - * LogoutUrlHelper provides generator functions for the logout URL. - * - * @author Jeremy Mikola - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class LogoutUrlHelper extends Helper -{ - private $generator; - - public function __construct(LogoutUrlGenerator $generator) - { - $this->generator = $generator; - } - - /** - * Generates the absolute logout path for the firewall. - * - * @param string|null $key The firewall key or null to use the current firewall key - * - * @return string The logout path - */ - public function getLogoutPath($key) - { - return $this->generator->getLogoutPath($key); - } - - /** - * Generates the absolute logout URL for the firewall. - * - * @param string|null $key The firewall key or null to use the current firewall key - * - * @return string The logout URL - */ - public function getLogoutUrl($key) - { - return $this->generator->getLogoutUrl($key); - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'logout_url'; - } -} diff --git a/src/Symfony/Bundle/SecurityBundle/Templating/Helper/SecurityHelper.php b/src/Symfony/Bundle/SecurityBundle/Templating/Helper/SecurityHelper.php deleted file mode 100644 index f6738bd3690df..0000000000000 --- a/src/Symfony/Bundle/SecurityBundle/Templating/Helper/SecurityHelper.php +++ /dev/null @@ -1,56 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\SecurityBundle\Templating\Helper; - -@trigger_error('The '.SecurityHelper::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Symfony\Component\Security\Acl\Voter\FieldVote; -use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; -use Symfony\Component\Templating\Helper\Helper; - -/** - * SecurityHelper provides read-only access to the security checker. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig instead. - */ -class SecurityHelper extends Helper -{ - private $securityChecker; - - public function __construct(AuthorizationCheckerInterface $securityChecker = null) - { - $this->securityChecker = $securityChecker; - } - - public function isGranted($role, $object = null, $field = null) - { - if (null === $this->securityChecker) { - return false; - } - - if (null !== $field) { - $object = new FieldVote($object, $field); - } - - return $this->securityChecker->isGranted($role, $object); - } - - /** - * {@inheritdoc} - */ - public function getName() - { - return 'security'; - } -} diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php index 450cb68ab119a..6fec33aea213a 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DataCollector/SecurityDataCollectorTest.php @@ -28,9 +28,7 @@ use Symfony\Component\Security\Core\Authorization\TraceableAccessDecisionManager; use Symfony\Component\Security\Core\Authorization\Voter\TraceableVoter; use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface; -use Symfony\Component\Security\Core\Role\Role; use Symfony\Component\Security\Core\Role\RoleHierarchy; -use Symfony\Component\Security\Core\Role\SwitchUserRole; use Symfony\Component\Security\Http\FirewallMapInterface; use Symfony\Component\Security\Http\Logout\LogoutUrlGenerator; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; @@ -97,36 +95,6 @@ public function testCollectAuthenticationTokenAndRoles(array $roles, array $norm $this->assertSame('hhamon', $collector->getUser()); } - /** - * @group legacy - */ - public function testCollectImpersonatedToken() - { - $adminToken = new UsernamePasswordToken('yceruto', 'P4$$w0rD', 'provider', ['ROLE_ADMIN']); - - $userRoles = [ - 'ROLE_USER', - new SwitchUserRole('ROLE_PREVIOUS_ADMIN', $adminToken), - ]; - - $tokenStorage = new TokenStorage(); - $tokenStorage->setToken(new UsernamePasswordToken('hhamon', 'P4$$w0rD', 'provider', $userRoles)); - - $collector = new SecurityDataCollector($tokenStorage, $this->getRoleHierarchy()); - $collector->collect(new Request(), new Response()); - $collector->lateCollect(); - - $this->assertTrue($collector->isEnabled()); - $this->assertTrue($collector->isAuthenticated()); - $this->assertTrue($collector->isImpersonated()); - $this->assertSame('yceruto', $collector->getImpersonatorUser()); - $this->assertSame('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $collector->getTokenClass()->getValue()); - $this->assertTrue($collector->supportsRoleHierarchy()); - $this->assertSame(['ROLE_USER', 'ROLE_PREVIOUS_ADMIN'], $collector->getRoles()->getValue(true)); - $this->assertSame([], $collector->getInheritedRoles()->getValue(true)); - $this->assertSame('hhamon', $collector->getUser()); - } - public function testCollectSwitchUserToken() { $adminToken = new UsernamePasswordToken('yceruto', 'P4$$w0rD', 'provider', ['ROLE_ADMIN']); @@ -390,22 +358,12 @@ public function provideRoles() ['ROLE_USER'], [], ], - [ - [new Role('ROLE_USER', false)], - ['ROLE_USER'], - [], - ], // Inherited roles [ ['ROLE_ADMIN'], ['ROLE_ADMIN'], ['ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'], ], - [ - [new Role('ROLE_ADMIN', false)], - ['ROLE_ADMIN'], - ['ROLE_USER', 'ROLE_ALLOWED_TO_SWITCH'], - ], [ ['ROLE_ADMIN', 'ROLE_OPERATOR'], ['ROLE_ADMIN', 'ROLE_OPERATOR'], diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSessionDomainConstraintPassTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSessionDomainConstraintPassTest.php index 7dcf7526bd552..8b9f59dbd9e3b 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSessionDomainConstraintPassTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Compiler/AddSessionDomainConstraintPassTest.php @@ -125,7 +125,6 @@ private function createContainer($sessionStorageOptions) $container->setParameter('kernel.container_class', 'cc'); $container->setParameter('kernel.debug', true); $container->setParameter('kernel.project_dir', __DIR__); - $container->setParameter('kernel.root_dir', __DIR__); $container->setParameter('kernel.secret', __DIR__); if (null !== $sessionStorageOptions) { $container->setParameter('session.storage.options', $sessionStorageOptions); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php index 8b1ce20bd57a7..59b79f354766f 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/CompleteConfigurationTest.php @@ -111,7 +111,6 @@ public function testFirewalls() [ 'parameter' => '_switch_user', 'role' => 'ROLE_ALLOWED_TO_SWITCH', - 'stateless' => false, ], ], [ @@ -286,7 +285,6 @@ public function testEncoders() 'cost' => null, 'memory_cost' => null, 'time_cost' => null, - 'threads' => null, 'migrate_from' => [], ], 'JMS\FooBundle\Entity\User3' => [ @@ -299,7 +297,6 @@ public function testEncoders() 'cost' => null, 'memory_cost' => null, 'time_cost' => null, - 'threads' => null, 'migrate_from' => [], ], 'JMS\FooBundle\Entity\User4' => new Reference('security.encoder.foo'), @@ -321,7 +318,6 @@ public function testEncoders() 'cost' => null, 'memory_cost' => null, 'time_cost' => null, - 'threads' => null, 'migrate_from' => [], ], ]], $container->getDefinition('security.encoder_factory.generic')->getArguments()); @@ -350,7 +346,6 @@ public function testEncodersWithLibsodium() 'cost' => null, 'memory_cost' => null, 'time_cost' => null, - 'threads' => null, 'migrate_from' => [], ], 'JMS\FooBundle\Entity\User3' => [ @@ -363,7 +358,6 @@ public function testEncodersWithLibsodium() 'cost' => null, 'memory_cost' => null, 'time_cost' => null, - 'threads' => null, 'migrate_from' => [], ], 'JMS\FooBundle\Entity\User4' => new Reference('security.encoder.foo'), @@ -405,7 +399,6 @@ public function testEncodersWithArgon2i() 'cost' => null, 'memory_cost' => null, 'time_cost' => null, - 'threads' => null, 'migrate_from' => [], ], 'JMS\FooBundle\Entity\User3' => [ @@ -418,7 +411,6 @@ public function testEncodersWithArgon2i() 'cost' => null, 'memory_cost' => null, 'time_cost' => null, - 'threads' => null, 'migrate_from' => [], ], 'JMS\FooBundle\Entity\User4' => new Reference('security.encoder.foo'), @@ -460,7 +452,6 @@ public function testMigratingEncoder() 'cost' => null, 'memory_cost' => null, 'time_cost' => null, - 'threads' => null, 'migrate_from' => [], ], 'JMS\FooBundle\Entity\User3' => [ @@ -473,7 +464,6 @@ public function testMigratingEncoder() 'cost' => null, 'memory_cost' => null, 'time_cost' => null, - 'threads' => null, 'migrate_from' => [], ], 'JMS\FooBundle\Entity\User4' => new Reference('security.encoder.foo'), @@ -495,7 +485,6 @@ public function testMigratingEncoder() 'cost' => null, 'memory_cost' => 256, 'time_cost' => 1, - 'threads' => null, 'migrate_from' => ['bcrypt'], ], ]], $container->getDefinition('security.encoder_factory.generic')->getArguments()); @@ -520,7 +509,6 @@ public function testEncodersWithBCrypt() 'cost' => null, 'memory_cost' => null, 'time_cost' => null, - 'threads' => null, 'migrate_from' => [], ], 'JMS\FooBundle\Entity\User3' => [ @@ -533,7 +521,6 @@ public function testEncodersWithBCrypt() 'cost' => null, 'memory_cost' => null, 'time_cost' => null, - 'threads' => null, 'migrate_from' => [], ], 'JMS\FooBundle\Entity\User4' => new Reference('security.encoder.foo'), @@ -644,64 +631,6 @@ public function testFirewallListenerWithProvider() $this->addToAssertionCount(1); } - /** - * @group legacy - * @expectedDeprecation The "simple_form" security listener is deprecated Symfony 4.2, use Guard instead. - */ - public function testSimpleAuth() - { - $container = $this->getContainer('simple_auth'); - $arguments = $container->getDefinition('security.firewall.map')->getArguments(); - $listeners = []; - $configs = []; - foreach (array_keys($arguments[1]->getValues()) as $contextId) { - $contextDef = $container->getDefinition($contextId); - $arguments = $contextDef->getArguments(); - $listeners[] = array_map('strval', $arguments['index_0']->getValues()); - - $configDef = $container->getDefinition((string) $arguments['index_3']); - $configs[] = array_values($configDef->getArguments()); - } - - $this->assertSame([[ - 'simple_auth', - 'security.user_checker', - null, - true, - false, - 'security.user.provider.concrete.default', - 'simple_auth', - 'security.authentication.form_entry_point.simple_auth', - null, - null, - ['simple_form', 'anonymous', - ], - null, - ]], $configs); - - $this->assertSame([[ - 'security.channel_listener', - 'security.context_listener.0', - 'security.authentication.listener.simple_form.simple_auth', - 'security.authentication.listener.anonymous.simple_auth', - 'security.access_listener', - ]], $listeners); - } - - /** - * @group legacy - * @expectedDeprecation Normalization of cookie names is deprecated since Symfony 4.3. Starting from Symfony 5.0, the "cookie1-name" cookie configured in "logout.delete_cookies" will delete the "cookie1-name" cookie instead of the "cookie1_name" cookie. - * @expectedDeprecation Normalization of cookie names is deprecated since Symfony 4.3. Starting from Symfony 5.0, the "cookie3-long_name" cookie configured in "logout.delete_cookies" will delete the "cookie3-long_name" cookie instead of the "cookie3_long_name" cookie. - */ - public function testLogoutDeleteCookieNamesNormalization() - { - $container = $this->getContainer('logout_delete_cookies'); - $cookiesToDelete = $container->getDefinition('security.logout.handler.cookie_clearing.main')->getArgument(0); - $expectedCookieNames = ['cookie2_name', 'cookie1_name', 'cookie3_long_name']; - - $this->assertSame($expectedCookieNames, array_keys($cookiesToDelete)); - } - protected function getContainer($file) { $file .= '.'.$this->getFileExtension(); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/php/simple_auth.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/php/simple_auth.php deleted file mode 100644 index 05829defd119d..0000000000000 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/php/simple_auth.php +++ /dev/null @@ -1,21 +0,0 @@ -loadFromExtension('security', [ - 'providers' => [ - 'default' => [ - 'memory' => [ - 'users' => [ - 'foo' => ['password' => 'foo', 'roles' => 'ROLE_USER'], - ], - ], - ], - ], - - 'firewalls' => [ - 'simple_auth' => [ - 'provider' => 'default', - 'anonymous' => true, - 'simple_form' => ['authenticator' => 'simple_authenticator'], - ], - ], -]); diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/xml/simple_auth.xml b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/xml/simple_auth.xml deleted file mode 100644 index 85fb312011bea..0000000000000 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/xml/simple_auth.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/yml/simple_auth.yml b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/yml/simple_auth.yml deleted file mode 100644 index b0f19e869b67c..0000000000000 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/Fixtures/yml/simple_auth.yml +++ /dev/null @@ -1,12 +0,0 @@ -security: - providers: - default: - memory: - users: - foo: { password: foo, roles: ROLE_USER } - - firewalls: - simple_auth: - provider: default - anonymous: ~ - simple_form: { authenticator: simple_authenticator } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php index 98624f747818e..8979ea8ded6a9 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/DependencyInjection/SecurityExtensionTest.php @@ -346,7 +346,6 @@ public function testRememberMeCookieInheritFrameworkSessionCookie($config, $same $container->registerExtension(new FrameworkExtension()); $container->setParameter('kernel.bundles_metadata', []); $container->setParameter('kernel.project_dir', __DIR__); - $container->setParameter('kernel.root_dir', __DIR__); $container->setParameter('kernel.cache_dir', __DIR__); $container->loadFromExtension('security', [ diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/Bundle/TestBundle.php b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/Bundle/TestBundle.php index 5197a16195e2e..d302b63791076 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/Bundle/TestBundle.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/Bundle/TestBundle.php @@ -25,14 +25,6 @@ public function build(ContainerBuilder $container) $container->setParameter('container.build_time', time()); $container->setParameter('container.build_id', 'test_bundle'); - $container->addCompilerPass(new class() implements CompilerPassInterface { - public function process(ContainerBuilder $container) - { - $container->removeDefinition('twig.controller.exception'); - $container->removeDefinition('twig.controller.preview_error'); - } - }); - $container->addCompilerPass(new CheckTypeDeclarationsPass(true), PassConfig::TYPE_AFTER_REMOVING, -100); } } diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/LocalizedRoutesAsPathTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/LocalizedRoutesAsPathTest.php index 2a45fc00de38f..b6d68fdd26b59 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/LocalizedRoutesAsPathTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/LocalizedRoutesAsPathTest.php @@ -35,6 +35,7 @@ public function testLoginLogoutProcedure($locale) } /** + * @group issue-32995 * @dataProvider getLocales */ public function testLoginFailureWithLocalizedFailurePath($locale) diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/config/twig.yml b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/config/twig.yml index f578e4b510378..493989866a278 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/config/twig.yml +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Functional/app/config/twig.yml @@ -2,4 +2,3 @@ twig: debug: '%kernel.debug%' strict_variables: '%kernel.debug%' - exception_controller: null # to be removed in 5.0 diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallContextTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallContextTest.php index 15f8764416099..c76783b7e08ad 100644 --- a/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallContextTest.php +++ b/src/Symfony/Bundle/SecurityBundle/Tests/Security/FirewallContextTest.php @@ -34,15 +34,6 @@ public function testGetters() $this->assertEquals($config, $context->getConfig()); } - /** - * @group legacy - * @expectedDeprecation Passing an instance of Symfony\Bundle\SecurityBundle\Security\FirewallConfig as the 3rd argument to "Symfony\Bundle\SecurityBundle\Security\FirewallContext::__construct()" is deprecated since Symfony 4.2. Pass a Symfony\Component\Security\Http\Firewall\LogoutListener instance instead. - */ - public function testFirewallConfigAs3rdConstructorArgument() - { - new FirewallContext([], $this->getExceptionListenerMock(), new FirewallConfig('main', 'user_checker', 'request_matcher')); - } - private function getExceptionListenerMock() { return $this diff --git a/src/Symfony/Bundle/SecurityBundle/Tests/SecurityUserValueResolverTest.php b/src/Symfony/Bundle/SecurityBundle/Tests/SecurityUserValueResolverTest.php deleted file mode 100644 index 177308277d08f..0000000000000 --- a/src/Symfony/Bundle/SecurityBundle/Tests/SecurityUserValueResolverTest.php +++ /dev/null @@ -1,96 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\SecurityBundle\Tests; - -use PHPUnit\Framework\TestCase; -use Symfony\Bundle\SecurityBundle\SecurityUserValueResolver; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpKernel\Controller\ArgumentResolver; -use Symfony\Component\HttpKernel\Controller\ArgumentResolver\DefaultValueResolver; -use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata; -use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage; -use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; -use Symfony\Component\Security\Core\User\UserInterface; - -/** - * @group legacy - */ -class SecurityUserValueResolverTest extends TestCase -{ - public function testResolveNoToken() - { - $tokenStorage = new TokenStorage(); - $resolver = new SecurityUserValueResolver($tokenStorage); - $metadata = new ArgumentMetadata('foo', UserInterface::class, false, false, null); - - $this->assertFalse($resolver->supports(Request::create('/'), $metadata)); - } - - public function testResolveNoUser() - { - $mock = $this->getMockBuilder(UserInterface::class)->getMock(); - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); - $tokenStorage = new TokenStorage(); - $tokenStorage->setToken($token); - - $resolver = new SecurityUserValueResolver($tokenStorage); - $metadata = new ArgumentMetadata('foo', \get_class($mock), false, false, null); - - $this->assertFalse($resolver->supports(Request::create('/'), $metadata)); - } - - public function testResolveWrongType() - { - $tokenStorage = new TokenStorage(); - $resolver = new SecurityUserValueResolver($tokenStorage); - $metadata = new ArgumentMetadata('foo', null, false, false, null); - - $this->assertFalse($resolver->supports(Request::create('/'), $metadata)); - } - - public function testResolve() - { - $user = $this->getMockBuilder(UserInterface::class)->getMock(); - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); - $token->expects($this->any())->method('getUser')->willReturn($user); - $tokenStorage = new TokenStorage(); - $tokenStorage->setToken($token); - - $resolver = new SecurityUserValueResolver($tokenStorage); - $metadata = new ArgumentMetadata('foo', UserInterface::class, false, false, null); - - $this->assertTrue($resolver->supports(Request::create('/'), $metadata)); - $this->assertSame([$user], iterator_to_array($resolver->resolve(Request::create('/'), $metadata))); - } - - public function testIntegration() - { - $user = $this->getMockBuilder(UserInterface::class)->getMock(); - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); - $token->expects($this->any())->method('getUser')->willReturn($user); - $tokenStorage = new TokenStorage(); - $tokenStorage->setToken($token); - - $argumentResolver = new ArgumentResolver(null, [new SecurityUserValueResolver($tokenStorage)]); - $this->assertSame([$user], $argumentResolver->getArguments(Request::create('/'), function (UserInterface $user) {})); - } - - public function testIntegrationNoUser() - { - $token = $this->getMockBuilder(TokenInterface::class)->getMock(); - $tokenStorage = new TokenStorage(); - $tokenStorage->setToken($token); - - $argumentResolver = new ArgumentResolver(null, [new SecurityUserValueResolver($tokenStorage), new DefaultValueResolver()]); - $this->assertSame([null], $argumentResolver->getArguments(Request::create('/'), function (UserInterface $user = null) {})); - } -} diff --git a/src/Symfony/Bundle/SecurityBundle/composer.json b/src/Symfony/Bundle/SecurityBundle/composer.json index 4ec8665479300..7ac48fa3d6395 100644 --- a/src/Symfony/Bundle/SecurityBundle/composer.json +++ b/src/Symfony/Bundle/SecurityBundle/composer.json @@ -16,38 +16,38 @@ } ], "require": { - "php": "^7.1.3", + "php": "^7.2.5", "ext-xml": "*", - "symfony/config": "^4.2|^5.0", + "symfony/config": "^4.4|^5.0", "symfony/dependency-injection": "^4.4|^5.0", - "symfony/http-kernel": "^4.4", - "symfony/security-core": "^4.4", - "symfony/security-csrf": "^4.2|^5.0", - "symfony/security-guard": "^4.2|^5.0", - "symfony/security-http": "^4.4" + "symfony/http-kernel": "^5.0", + "symfony/security-core": "^4.4|^5.0", + "symfony/security-csrf": "^4.4|^5.0", + "symfony/security-guard": "^4.4|^5.0", + "symfony/security-http": "^4.4|^5.0" }, "require-dev": { "doctrine/doctrine-bundle": "^1.5|^2.0", - "symfony/asset": "^3.4|^4.0|^5.0", - "symfony/browser-kit": "^4.2|^5.0", - "symfony/console": "^3.4|^4.0|^5.0", - "symfony/css-selector": "^3.4|^4.0|^5.0", - "symfony/dom-crawler": "^3.4|^4.0|^5.0", - "symfony/expression-language": "^3.4|^4.0|^5.0", - "symfony/form": "^3.4|^4.0|^5.0", + "symfony/asset": "^4.4|^5.0", + "symfony/browser-kit": "^4.4|^5.0", + "symfony/console": "^4.4|^5.0", + "symfony/css-selector": "^4.4|^5.0", + "symfony/dom-crawler": "^4.4|^5.0", + "symfony/expression-language": "^4.4|^5.0", + "symfony/form": "^4.4|^5.0", "symfony/framework-bundle": "^4.4|^5.0", - "symfony/process": "^3.4|^4.0|^5.0", + "symfony/process": "^4.4|^5.0", "symfony/serializer": "^4.4|^5.0", - "symfony/translation": "^3.4|^4.0|^5.0", - "symfony/twig-bridge": "^3.4|^4.0|^5.0", + "symfony/translation": "^4.4|^5.0", "symfony/twig-bundle": "^4.4|^5.0", - "symfony/validator": "^3.4|^4.0|^5.0", - "symfony/yaml": "^3.4|^4.0|^5.0", - "twig/twig": "^1.41|^2.10|^3.0" + "symfony/twig-bridge": "^4.4|^5.0", + "symfony/validator": "^4.4|^5.0", + "symfony/yaml": "^4.4|^5.0", + "twig/twig": "^2.10|^3.0" }, "conflict": { - "symfony/browser-kit": "<4.2", - "symfony/console": "<3.4", + "symfony/browser-kit": "<4.4", + "symfony/console": "<4.4", "symfony/framework-bundle": "<4.4", "symfony/ldap": "<4.4", "symfony/twig-bundle": "<4.4" @@ -61,7 +61,7 @@ "minimum-stability": "dev", "extra": { "branch-alias": { - "dev-master": "4.4-dev" + "dev-master": "5.1-dev" } } } diff --git a/src/Symfony/Bundle/TwigBundle/CHANGELOG.md b/src/Symfony/Bundle/TwigBundle/CHANGELOG.md index 780c46466dd36..f07bf65d3e1fc 100644 --- a/src/Symfony/Bundle/TwigBundle/CHANGELOG.md +++ b/src/Symfony/Bundle/TwigBundle/CHANGELOG.md @@ -1,6 +1,16 @@ CHANGELOG ========= +5.0.0 +----- + + * updated default value for the `strict_variables` option to `%kernel.debug%` parameter + * removed support to load templates from the legacy directories `src/Resources/views/` and `src/Resources//views/` + * removed `TwigEngine` class, use `Twig\Environment` instead + * removed `FilesystemLoader` and `NativeFilesystemLoader`, use Twig notation for templates instead + * removed `twig.exception_controller` configuration option, use `framework.error_controller` option instead + * removed `ExceptionController`, `PreviewErrorController` and all built-in error templates in favor of the new error renderer mechanism + 4.4.0 ----- diff --git a/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheCacheWarmer.php b/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheCacheWarmer.php deleted file mode 100644 index 0df14ca0f4131..0000000000000 --- a/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheCacheWarmer.php +++ /dev/null @@ -1,122 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\TwigBundle\CacheWarmer; - -@trigger_error('The '.TemplateCacheCacheWarmer::class.' class is deprecated since version 4.4 and will be removed in 5.0; use Twig instead.', E_USER_DEPRECATED); - -use Psr\Container\ContainerInterface; -use Symfony\Bundle\FrameworkBundle\CacheWarmer\TemplateFinderInterface; -use Symfony\Bundle\TwigBundle\DependencyInjection\CompatibilityServiceSubscriberInterface as ServiceSubscriberInterface; -use Symfony\Component\Finder\Finder; -use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; -use Twig\Environment; -use Twig\Error\Error; - -/** - * Generates the Twig cache for all templates. - * - * This warmer must be registered after TemplatePathsCacheWarmer, - * as the Twig loader will need the cache generated by it. - * - * @author Fabien Potencier - * - * @deprecated since version 4.4, to be removed in 5.0; use Twig instead. - */ -class TemplateCacheCacheWarmer implements CacheWarmerInterface, ServiceSubscriberInterface -{ - protected $container; - protected $finder; - private $paths; - - /** - * @param array $paths Additional twig paths to warm - */ - public function __construct(ContainerInterface $container, TemplateFinderInterface $finder = null, array $paths = []) - { - // We don't inject the Twig environment directly as it depends on the - // template locator (via the loader) which might be a cached one. - // The cached template locator is available once the TemplatePathsCacheWarmer - // has been warmed up. - // But it can also be null if templating has been disabled. - $this->container = $container; - $this->finder = $finder; - $this->paths = $paths; - } - - /** - * Warms up the cache. - * - * @param string $cacheDir The cache directory - */ - public function warmUp($cacheDir) - { - if (null === $this->finder) { - return; - } - - $twig = $this->container->get('twig'); - - $templates = $this->finder->findAllTemplates(); - - foreach ($this->paths as $path => $namespace) { - $templates = array_merge($templates, $this->findTemplatesInFolder($namespace, $path)); - } - - foreach ($templates as $template) { - try { - $twig->load($template); - } catch (Error $e) { - // problem during compilation, give up - } - } - } - - /** - * Checks whether this warmer is optional or not. - * - * @return bool always true - */ - public function isOptional() - { - return true; - } - - /** - * {@inheritdoc} - */ - public static function getSubscribedServices() - { - return [ - 'twig' => Environment::class, - ]; - } - - /** - * Find templates in the given directory. - */ - private function findTemplatesInFolder(?string $namespace, string $dir): array - { - if (!is_dir($dir)) { - return []; - } - - $templates = []; - $finder = new Finder(); - - foreach ($finder->files()->followLinks()->in($dir) as $file) { - $name = $file->getRelativePathname(); - $templates[] = $namespace ? sprintf('@%s/%s', $namespace, $name) : $name; - } - - return $templates; - } -} diff --git a/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheWarmer.php b/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheWarmer.php index e81ac2ab859d9..c5fb5c8fbefc8 100644 --- a/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheWarmer.php +++ b/src/Symfony/Bundle/TwigBundle/CacheWarmer/TemplateCacheWarmer.php @@ -12,8 +12,8 @@ namespace Symfony\Bundle\TwigBundle\CacheWarmer; use Psr\Container\ContainerInterface; -use Symfony\Bundle\TwigBundle\DependencyInjection\CompatibilityServiceSubscriberInterface as ServiceSubscriberInterface; use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface; +use Symfony\Contracts\Service\ServiceSubscriberInterface; use Twig\Environment; use Twig\Error\Error; @@ -38,7 +38,7 @@ public function __construct(ContainerInterface $container, iterable $iterator) /** * {@inheritdoc} */ - public function warmUp($cacheDir) + public function warmUp(string $cacheDir) { if (null === $this->twig) { $this->twig = $this->container->get('twig'); diff --git a/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php b/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php index 386653eb22d90..f6e6b054faf56 100644 --- a/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php +++ b/src/Symfony/Bundle/TwigBundle/Command/LintCommand.php @@ -42,7 +42,7 @@ protected function configure() ; } - protected function findFiles($filename): iterable + protected function findFiles(string $filename): iterable { if (0 === strpos($filename, '@')) { $dir = $this->getApplication()->getKernel()->locateResource($filename); diff --git a/src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php b/src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php deleted file mode 100644 index c679d9a772029..0000000000000 --- a/src/Symfony/Bundle/TwigBundle/Controller/ExceptionController.php +++ /dev/null @@ -1,152 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\TwigBundle\Controller; - -use Symfony\Component\Debug\Exception\FlattenException; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpFoundation\Response; -use Symfony\Component\HttpKernel\Log\DebugLoggerInterface; -use Twig\Environment; -use Twig\Error\LoaderError; -use Twig\Loader\ExistsLoaderInterface; -use Twig\Loader\SourceContextLoaderInterface; - -@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.4, use "%s" instead.', ExceptionController::class, \Symfony\Component\HttpKernel\Controller\ErrorController::class), E_USER_DEPRECATED); - -/** - * ExceptionController renders error or exception pages for a given - * FlattenException. - * - * @author Fabien Potencier - * @author Matthias Pigulla - * - * @deprecated since Symfony 4.4, use Symfony\Component\HttpKernel\Controller\ErrorController instead. - */ -class ExceptionController -{ - protected $twig; - protected $debug; - - /** - * @param bool $debug Show error (false) or exception (true) pages by default - */ - public function __construct(Environment $twig, bool $debug) - { - $this->twig = $twig; - $this->debug = $debug; - } - - /** - * Converts an Exception to a Response. - * - * A "showException" request parameter can be used to force display of an error page (when set to false) or - * the exception page (when true). If it is not present, the "debug" value passed into the constructor will - * be used. - * - * @return Response - * - * @throws \InvalidArgumentException When the exception template does not exist - */ - public function showAction(Request $request, FlattenException $exception, DebugLoggerInterface $logger = null) - { - $currentContent = $this->getAndCleanOutputBuffering($request->headers->get('X-Php-Ob-Level', -1)); - $showException = $request->attributes->get('showException', $this->debug); // As opposed to an additional parameter, this maintains BC - - $code = $exception->getStatusCode(); - - return new Response($this->twig->render( - (string) $this->findTemplate($request, $request->getRequestFormat(), $code, $showException), - [ - 'status_code' => $code, - 'status_text' => isset(Response::$statusTexts[$code]) ? Response::$statusTexts[$code] : '', - 'exception' => $exception, - 'logger' => $logger, - 'currentContent' => $currentContent, - ] - ), 200, ['Content-Type' => $request->getMimeType($request->getRequestFormat()) ?: 'text/html']); - } - - /** - * @param int $startObLevel - * - * @return string - */ - protected function getAndCleanOutputBuffering($startObLevel) - { - if (ob_get_level() <= $startObLevel) { - return ''; - } - - Response::closeOutputBuffers($startObLevel + 1, true); - - return ob_get_clean(); - } - - /** - * @param string $format - * @param int $code An HTTP response status code - * @param bool $showException - * - * @return string - */ - protected function findTemplate(Request $request, $format, $code, $showException) - { - $name = $showException ? 'exception' : 'error'; - if ($showException && 'html' == $format) { - $name = 'exception_full'; - } - - // For error pages, try to find a template for the specific HTTP status code and format - if (!$showException) { - $template = sprintf('@Twig/Exception/%s%s.%s.twig', $name, $code, $format); - if ($this->templateExists($template)) { - return $template; - } - } - - // try to find a template for the given format - $template = sprintf('@Twig/Exception/%s.%s.twig', $name, $format); - if ($this->templateExists($template)) { - return $template; - } - - // default to a generic HTML exception - $request->setRequestFormat('html'); - - return sprintf('@Twig/Exception/%s.html.twig', $showException ? 'exception_full' : $name); - } - - // 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 (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; - } - - return $loader->exists($template); - } -} diff --git a/src/Symfony/Bundle/TwigBundle/Controller/PreviewErrorController.php b/src/Symfony/Bundle/TwigBundle/Controller/PreviewErrorController.php deleted file mode 100644 index e8f66d0f049a6..0000000000000 --- a/src/Symfony/Bundle/TwigBundle/Controller/PreviewErrorController.php +++ /dev/null @@ -1,60 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\TwigBundle\Controller; - -use Symfony\Component\Debug\Exception\FlattenException; -use Symfony\Component\HttpFoundation\Request; -use Symfony\Component\HttpKernel\HttpKernelInterface; - -@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.4, use the "%s" instead.', PreviewErrorController::class, \Symfony\Component\HttpKernel\Controller\ErrorController::class), E_USER_DEPRECATED); - -/** - * PreviewErrorController can be used to test error pages. - * - * It will create a test exception and forward it to another controller. - * - * @author Matthias Pigulla - * - * @deprecated since Symfony 4.4, use the Symfony\Component\HttpKernel\Controller\ErrorController instead. - */ -class PreviewErrorController -{ - protected $kernel; - protected $controller; - - public function __construct(HttpKernelInterface $kernel, $controller) - { - $this->kernel = $kernel; - $this->controller = $controller; - } - - public function previewErrorPageAction(Request $request, $code) - { - $exception = FlattenException::createFromThrowable(new \Exception('Something has intentionally gone wrong.'), $code); - - /* - * This Request mimics the parameters set by - * \Symfony\Component\HttpKernel\EventListener\ErrorListener::duplicateRequest, with - * the additional "showException" flag. - */ - - $subRequest = $request->duplicate(null, null, [ - '_controller' => $this->controller, - 'exception' => $exception, - 'logger' => null, - 'format' => $request->getRequestFormat(), - 'showException' => false, - ]); - - return $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST); - } -} diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/CompatibilityServiceSubscriberInterface.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/CompatibilityServiceSubscriberInterface.php deleted file mode 100644 index 967f732ff59f9..0000000000000 --- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/CompatibilityServiceSubscriberInterface.php +++ /dev/null @@ -1,31 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\TwigBundle\DependencyInjection; - -use Symfony\Component\DependencyInjection\ServiceSubscriberInterface as LegacyServiceSubscriberInterface; -use Symfony\Contracts\Service\ServiceSubscriberInterface; - -if (interface_exists(LegacyServiceSubscriberInterface::class)) { - /** - * @internal - */ - interface CompatibilityServiceSubscriberInterface extends LegacyServiceSubscriberInterface - { - } -} else { - /** - * @internal - */ - interface CompatibilityServiceSubscriberInterface extends ServiceSubscriberInterface - { - } -} diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/ExceptionListenerPass.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/ExceptionListenerPass.php deleted file mode 100644 index d06b8e8199c20..0000000000000 --- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/ExceptionListenerPass.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\TwigBundle\DependencyInjection\Compiler; - -use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; -use Symfony\Component\DependencyInjection\ContainerBuilder; - -/** - * Registers the Twig exception listener if Twig is registered as a templating engine. - * - * @author Fabien Potencier - * - * @internal - */ -class ExceptionListenerPass implements CompilerPassInterface -{ - public function process(ContainerBuilder $container) - { - if (false === $container->hasDefinition('twig')) { - return; - } - - // to be removed in 5.0 - // register the exception listener only if it's currently used, else use the provided by FrameworkBundle - if (null === $container->getParameter('twig.exception_listener.controller') && $container->hasDefinition('exception_listener')) { - $container->removeDefinition('twig.exception_listener'); - } else { - $container->removeDefinition('exception_listener'); - - if ($container->hasParameter('templating.engines')) { - $engines = $container->getParameter('templating.engines'); - if (!\in_array('twig', $engines, true)) { - $container->removeDefinition('twig.exception_listener'); - } - } - } - } -} diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/ExtensionPass.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/ExtensionPass.php index c6b0aaa5846cd..6c955aae6fa50 100644 --- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/ExtensionPass.php +++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Compiler/ExtensionPass.php @@ -14,7 +14,6 @@ use Symfony\Component\DependencyInjection\Alias; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; -use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\Workflow\Workflow; /** @@ -42,7 +41,7 @@ public function process(ContainerBuilder $container) $viewDir = \dirname((new \ReflectionClass('Symfony\Bridge\Twig\Extension\FormExtension'))->getFileName(), 2).'/Resources/views'; $templateIterator = $container->getDefinition('twig.template_iterator'); - $templatePaths = $templateIterator->getArgument(2); + $templatePaths = $templateIterator->getArgument(1); $cacheWarmer = null; if ($container->hasDefinition('twig.cache_warmer')) { $cacheWarmer = $container->getDefinition('twig.cache_warmer'); @@ -71,7 +70,7 @@ public function process(ContainerBuilder $container) } } - $templateIterator->replaceArgument(2, $templatePaths); + $templateIterator->replaceArgument(1, $templatePaths); if ($cacheWarmer) { $container->getDefinition('twig.cache_warmer')->replaceArgument(2, $cacheWarmerPaths); } @@ -84,11 +83,9 @@ public function process(ContainerBuilder $container) $container->getDefinition('twig.extension.httpkernel')->addTag('twig.extension'); $container->getDefinition('twig.runtime.httpkernel')->addTag('twig.runtime'); - // inject Twig in the hinclude service if Twig is the only registered templating engine - if ((!$container->hasParameter('templating.engines') || ['twig'] == $container->getParameter('templating.engines')) && $container->hasDefinition('fragment.renderer.hinclude')) { + if ($container->hasDefinition('fragment.renderer.hinclude')) { $container->getDefinition('fragment.renderer.hinclude') ->addTag('kernel.fragment_renderer', ['alias' => 'hinclude']) - ->replaceArgument(0, new Reference('twig')) ; } } @@ -114,17 +111,7 @@ public function process(ContainerBuilder $container) $container->getDefinition('twig.extension.weblink')->addTag('twig.extension'); } - $twigLoader = $container->getDefinition('twig.loader.native_filesystem'); - if ($container->has('templating')) { - $loader = $container->getDefinition('twig.loader.filesystem'); - $loader->setMethodCalls(array_merge($twigLoader->getMethodCalls(), $loader->getMethodCalls())); - - $twigLoader->clearTag('twig.loader'); - } else { - $container->setAlias('twig.loader.filesystem', new Alias('twig.loader.native_filesystem', false)); - $container->removeDefinition('templating.engine.twig'); - $container->removeDefinition('twig.cache_warmer'); - } + $container->setAlias('twig.loader.filesystem', new Alias('twig.loader.native_filesystem', false)); if ($container->has('assets.packages')) { $container->getDefinition('twig.extension.assets')->addTag('twig.extension'); diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php index 99be854a0cc45..8c763f737c07c 100644 --- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php +++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/Configuration.php @@ -14,6 +14,7 @@ use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; +use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException; /** * TwigExtension configuration structure. @@ -32,25 +33,18 @@ public function getConfigTreeBuilder() $treeBuilder = new TreeBuilder('twig'); $rootNode = $treeBuilder->getRootNode(); - $rootNode - ->children() - ->scalarNode('exception_controller') - ->defaultValue(static function () { - @trigger_error('The "twig.exception_controller" configuration key has been deprecated in Symfony 4.4, set it to "null" and use "framework.error_controller" configuration key instead.', E_USER_DEPRECATED); + $rootNode->beforeNormalization() + ->ifTrue(function ($v) { return \is_array($v) && \array_key_exists('exception_controller', $v); }) + ->then(function ($v) { + if (isset($v['exception_controller'])) { + throw new InvalidConfigurationException('Option "exception_controller" under "twig" must be null or unset, use "error_controller" under "framework" instead.'); + } - return 'twig.controller.exception::showAction'; - }) - ->validate() - ->ifTrue(static function ($v) { return null !== $v; }) - ->then(static function ($v) { - @trigger_error('The "twig.exception_controller" configuration key has been deprecated in Symfony 4.4, set it to "null" and use "framework.error_controller" configuration key instead.', E_USER_DEPRECATED); + unset($v['exception_controller']); - return $v; - }) - ->end() - ->end() - ->end() - ; + return $v; + }) + ->end(); $this->addFormThemesSection($rootNode); $this->addGlobalsSection($rootNode); @@ -142,13 +136,7 @@ private function addTwigOptions(ArrayNodeDefinition $rootNode) ->scalarNode('cache')->defaultValue('%kernel.cache_dir%/twig')->end() ->scalarNode('charset')->defaultValue('%kernel.charset%')->end() ->booleanNode('debug')->defaultValue('%kernel.debug%')->end() - ->booleanNode('strict_variables') - ->defaultValue(function () { - @trigger_error('Relying on the default value ("false") of the "twig.strict_variables" configuration option is deprecated since Symfony 4.1. You should use "%kernel.debug%" explicitly instead, which will be the new default in 5.0.', E_USER_DEPRECATED); - - return false; - }) - ->end() + ->booleanNode('strict_variables')->defaultValue('%kernel.debug%')->end() ->scalarNode('auto_reload')->end() ->integerNode('optimizations')->min(-1)->end() ->scalarNode('default_path') diff --git a/src/Symfony/Bundle/TwigBundle/DependencyInjection/TwigExtension.php b/src/Symfony/Bundle/TwigBundle/DependencyInjection/TwigExtension.php index 9d2447aed42b3..a70fd31afe3f8 100644 --- a/src/Symfony/Bundle/TwigBundle/DependencyInjection/TwigExtension.php +++ b/src/Symfony/Bundle/TwigBundle/DependencyInjection/TwigExtension.php @@ -11,7 +11,6 @@ namespace Symfony\Bundle\TwigBundle\DependencyInjection; -use Symfony\Bundle\TwigBundle\Loader\NativeFilesystemLoader; use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\Resource\FileExistenceResource; use Symfony\Component\Console\Application; @@ -42,10 +41,6 @@ public function load(array $configs, ContainerBuilder $container) $loader->load('form.xml'); } - if (interface_exists('Symfony\Component\Templating\EngineInterface')) { - $loader->load('templating.xml'); - } - if (class_exists(Application::class)) { $loader->load('console.xml'); } @@ -75,8 +70,6 @@ public function load(array $configs, ContainerBuilder $container) $config = $this->processConfiguration($configuration, $configs); - $container->setParameter('twig.exception_listener.controller', $config['exception_controller']); - $container->setParameter('twig.form.resources', $config['form_themes']); $container->setParameter('twig.default_path', $config['default_path']); $defaultTwigPath = $container->getParameterBag()->resolveValue($config['default_path']); @@ -91,10 +84,6 @@ public function load(array $configs, ContainerBuilder $container) $twigFilesystemLoaderDefinition = $container->getDefinition('twig.loader.native_filesystem'); - if ($container->getParameter('kernel.debug')) { - $twigFilesystemLoaderDefinition->setClass(NativeFilesystemLoader::class); - } - // register user-configured paths foreach ($config['paths'] as $path => $namespace) { if (!$namespace) { @@ -105,8 +94,7 @@ public function load(array $configs, ContainerBuilder $container) } // paths are modified in ExtensionPass if forms are enabled - $container->getDefinition('twig.cache_warmer')->replaceArgument(2, $config['paths']); - $container->getDefinition('twig.template_iterator')->replaceArgument(2, $config['paths']); + $container->getDefinition('twig.template_iterator')->replaceArgument(1, $config['paths']); foreach ($this->getBundleTemplatePaths($container, $config) as $name => $paths) { $namespace = $this->normalizeBundleName($name); @@ -120,15 +108,6 @@ public function load(array $configs, ContainerBuilder $container) } } - if (file_exists($dir = $container->getParameter('kernel.root_dir').'/Resources/views')) { - if ($dir !== $defaultTwigPath) { - @trigger_error(sprintf('Loading Twig templates from the "%s" directory is deprecated since Symfony 4.2, use "%s" instead.', $dir, $defaultTwigPath), E_USER_DEPRECATED); - } - - $twigFilesystemLoaderDefinition->addMethodCall('addPath', [$dir]); - } - $container->addResource(new FileExistenceResource($dir)); - if (file_exists($defaultTwigPath)) { $twigFilesystemLoaderDefinition->addMethodCall('addPath', [$defaultTwigPath]); } @@ -167,7 +146,6 @@ public function load(array $configs, ContainerBuilder $container) $container->registerForAutoconfiguration(RuntimeExtensionInterface::class)->addTag('twig.runtime'); if (false === $config['cache']) { - $container->removeDefinition('twig.cache_warmer'); $container->removeDefinition('twig.template_cache_warmer'); } } @@ -178,13 +156,6 @@ private function getBundleTemplatePaths(ContainerBuilder $container, array $conf foreach ($container->getParameter('kernel.bundles_metadata') as $name => $bundle) { $defaultOverrideBundlePath = $container->getParameterBag()->resolveValue($config['default_path']).'/bundles/'.$name; - if (file_exists($dir = $container->getParameter('kernel.root_dir').'/Resources/'.$name.'/views')) { - @trigger_error(sprintf('Loading Twig templates for "%s" from the "%s" directory is deprecated since Symfony 4.2, use "%s" instead.', $name, $dir, $defaultOverrideBundlePath), E_USER_DEPRECATED); - - $bundleHierarchy[$name][] = $dir; - } - $container->addResource(new FileExistenceResource($dir)); - if (file_exists($defaultOverrideBundlePath)) { $bundleHierarchy[$name][] = $defaultOverrideBundlePath; } diff --git a/src/Symfony/Bundle/TwigBundle/Loader/FilesystemLoader.php b/src/Symfony/Bundle/TwigBundle/Loader/FilesystemLoader.php deleted file mode 100644 index 3f6179d27f4db..0000000000000 --- a/src/Symfony/Bundle/TwigBundle/Loader/FilesystemLoader.php +++ /dev/null @@ -1,104 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\TwigBundle\Loader; - -@trigger_error('The '.FilesystemLoader::class.' class is deprecated since version 4.3 and will be removed in 5.0; use Twig notation for templates instead.', E_USER_DEPRECATED); - -use Symfony\Component\Config\FileLocatorInterface; -use Symfony\Component\Templating\TemplateNameParserInterface; -use Symfony\Component\Templating\TemplateReferenceInterface; -use Twig\Error\LoaderError; -use Twig\Loader\FilesystemLoader as BaseFilesystemLoader; - -/** - * FilesystemLoader extends the default Twig filesystem loader - * to work with the Symfony paths and template references. - * - * @author Fabien Potencier - * - * @deprecated since version 4.3, to be removed in 5.0; use Twig notation for templates instead. - */ -class FilesystemLoader extends BaseFilesystemLoader -{ - protected $locator; - protected $parser; - - /** - * @param string|null $rootPath The root path common to all relative paths (null for getcwd()) - */ - public function __construct(FileLocatorInterface $locator, TemplateNameParserInterface $parser, string $rootPath = null) - { - parent::__construct([], $rootPath); - - $this->locator = $locator; - $this->parser = $parser; - } - - /** - * {@inheritdoc} - * - * The name parameter might also be a TemplateReferenceInterface. - * - * @return bool - */ - public function exists($name) - { - return parent::exists((string) $name); - } - - /** - * Returns the path to the template file. - * - * The file locator is used to locate the template when the naming convention - * is the symfony one (i.e. the name can be parsed). - * Otherwise the template is located using the locator from the twig library. - * - * @param string|TemplateReferenceInterface $template The template - * @param bool $throw When true, a LoaderError exception will be thrown if a template could not be found - * - * @return string The path to the template file - * - * @throws LoaderError if the template could not be found - */ - protected function findTemplate($template, $throw = true) - { - $logicalName = (string) $template; - - if (isset($this->cache[$logicalName])) { - return $this->cache[$logicalName]; - } - - $file = null; - try { - $file = parent::findTemplate($logicalName); - } catch (LoaderError $e) { - $twigLoaderException = $e; - - // for BC - try { - $template = $this->parser->parse($template); - $file = $this->locator->locate($template); - } catch (\Exception $e) { - } - } - - if (false === $file || null === $file) { - if ($throw) { - throw $twigLoaderException; - } - - return false; - } - - return $this->cache[$logicalName] = $file; - } -} diff --git a/src/Symfony/Bundle/TwigBundle/Loader/NativeFilesystemLoader.php b/src/Symfony/Bundle/TwigBundle/Loader/NativeFilesystemLoader.php deleted file mode 100644 index 493fe250779df..0000000000000 --- a/src/Symfony/Bundle/TwigBundle/Loader/NativeFilesystemLoader.php +++ /dev/null @@ -1,52 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Symfony\Bundle\TwigBundle\Loader; - -use Twig\Error\LoaderError; -use Twig\Loader\FilesystemLoader; - -/** - * @author Behnoush Norouzali - * - * @internal - */ -class NativeFilesystemLoader extends FilesystemLoader -{ - /** - * {@inheritdoc} - * - * @return string|null - */ - protected function findTemplate($template, $throw = true) - { - try { - return parent::findTemplate($template, $throw); - } catch (LoaderError $e) { - if ('' === $template || '@' === $template[0] || !preg_match('/^(?P[^:]*?)(?:Bundle)?:(?P[^:]*+):(?P