Quantcast
Channel: Symfony Blog
Viewing all 3133 articles
Browse latest View live

New in Symfony 5.1: Serializer improvements

$
0
0

Added @Ignore annotation

Kévin Dunglas

Contributed by
Kévin Dunglas
in #28744.

Symfony 5.1 adds a new @Ignore annotation to allow ignoring some values when serializing. You can apply the annotation both to properties and methods. Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
useSymfony\Component\Serializer\Annotation\Ignore;classSomeClass{public$someProperty;/**     * @Ignore()     */public$anotherProperty;private$lastProperty;/**     * @Ignore()     */publicfunctiongetLastProperty(){return$this->lastProperty;}}

This is also available in YAML and XML formats using the ignore option:

1
2
3
4
5
6
7
App\SomePath\SomeClas:attributes:# ...anotherProperty:ignore:truelastProperty:ignore:true
1
2
3
4
5
<classname="App\SomePath\SomeClass"><!-- ... --><attributename="anotherProperty"ignore="true"/><attributename="lastProperty"ignore="true"/></class>

Unwrapping Denormalizer

Eduard Bulava

Contributed by
Eduard Bulava
in #31390.

APIs often return nested responses in which you only need some child object. In Symfony 5.1, thanks to the new UnwrappingDenormalizer, you can get any nested object without creating unnecessary model classes:

1
2
3
4
5
6
7
8
useSymfony\Component\Serializer\Normalizer\UnwrappingDenormalizer;$result=$serialiser->deserialize('{"baz": {"foo": "bar", "inner": {"title": "value", "numbers": [5,3]}}}',Object::class,[UnwrappingDenormalizer::UNWRAP_PATH=>'[baz][inner]']);// $result->title === 'value'

Added support for stdClass

Kévin Dunglas

Contributed by
Kévin Dunglas
in #35596.

When an object contains properties of PHP stdClass, serialization fails. In Symfony 5.1 we've added support for it:

1
2
3
4
5
$object=new\stdClass();$object->foo='f';$object->bar='b';$normalizer->normalize($object)===['foo'=>'f','bar'=>'b']

Scalar denormalization

Alexander Menshchikov

Contributed by
Alexander Menshchikov
in #35235.

In Symfony 5.1 we also added support for scalar values denormalization. These scalar values are numbers (int or float), booleans and strings. The following example shows how can you normalize and denormalize those values:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
useSymfony\Component\Serializer\Encoder\JsonEncoder;useSymfony\Component\Serializer\Normalizer\ArrayDenormalizer;useSymfony\Component\Serializer\Serializer;$serializer=newSerializer([],['json'=>newJsonEncoder()]);'42'===$serializer->serialize(42,'json')'true'===$serializer->serialize(true,'json')'3.14'===$serializer->serialize(3.14,'json')'foo bar'===$serializer->serialize('foo bar','json')$serializer=newSerializer([newArrayDenormalizer()],['json'=>newJsonEncoder()]);[42]===$serializer->deserialize('[42]','int[]','json')[true,false]===$serializer->deserialize('[true,false]','bool[]','json')[3.14]===$serializer->deserialize('[3.14]','float[]','json')['foo bar']===$serializer->deserialize('["foo bar"]','string[]','json')

Sponsor the Symfony project.

French SymfonyLive Online conference on May 7th 2020

$
0
0

While we wait for the postponed SymfonyLive Paris 2020 conference which will take place on September 23-24 2020, we’re pleased to organize a special SymfonyLive Online conference in French on May 7th 2020. This special online session is only reserved for the attendees of SymfonyLive Paris 2020 to thank them for their patience and confidence. As the conference is organized in French, the following blog post will be written in French.


En attendant le report de la conférence Symfony parisienne, les 23 et 24 septembre 2020, nous avons le plaisir de vous annoncer que nous organisons une édition spéciale de la conférence SymfonyLive Online en français le jeudi 7 mai 2020 à 17h, réservée exclusivement aux personnes inscrites au SymfonyLive Paris 2020. N'ayant malheureusement pas pu vous retrouver fin mars, pour remercier les participants déjà inscrits à la conférence parisienne reportée de leur patience, leur confiance et leur soutien, nous vous proposons de vous retrouver virtuellement jeudi prochain pour une conférence exclusive en français.

Ecoutez Fabien Potencier et Nicolas Grekas lors de cette édition spéciale en français vous présenter des talks de 40 minutes chacun. Si vous êtes déjà inscrit au SymfonyLive Paris 2020, vous êtes automatiquement inscrit à la conférence en ligne du 7 mai. Voici l'agenda de la conférence en ligne :

  • The Symfony Notifier Component (40 min) par Fabien Potencier, project lead de Symfony, fondateur/CEO de Blackfire et Symfony SAS. Le composant Notifier est disponible depuis Symfony 5.0. Il est basé sur le travail effectué ces dernières années sur les composants Mailer, HttpClient et Messenger. Apprenez tout ce que vous devez savoir sur son utilisation au sein de vos propres applications.

  • Preloading and Symfony, a love story (40 min) par Nicolas Grekas, core contributor de Symfony, principal engineer chez Symfony SAS. Le preloading est un sujet chaud de l'actualité PHP. Depuis ses premières expérimentations en septembre (et les rapports de crash), Nicolas traque la bête. La toute récente version 7.4.5 de PHP nous permet enfin de l'envisager sur des applications non triviales. Sur un "Hello World", il a mesuré des gains très significatifs. Mais pour maximiser le bénéfice du preloading, quelques aménagements ont été nécessaires dans Symfony, et d'autres le seront dans vos apps et autres bundles. Je vous propose de les passer en revu et de vous montrer comment booster le temps de réponse de vos serveurs à moindre frais.

Si vous n'êtes pas inscrit au SymfonyLive Paris 2020 des 23 et 24 septembre, rejoignez-nous pour la 12e édition de la conférence et participez également à la conférence SymfonyLive Online du 7 mai prochain ! Prenez votre billet unique et assistez à 2 événements : le 7 mai à 17h depuis chez vous et les 23 et 24 septembre à la Cité Internationale Universitaire. Le planning complet du SymfonyLive Paris 2020 reste inchangé.

Rendez-vous la semaine prochaine pour la session en ligne, nous avons hâte de vous retrouver pour cette première session en ligne en français ! Nous souhaitons remercier la communauté Symfony pour son soutien durant cette période et sommes impatients de vous retrouver fin septembre. En attendant, restez chez vous et soyez prudent.


Sponsor the Symfony project.

A Week of Symfony #696 (27 April - 3 May 2020)

$
0
0

This week, Symfony 3.4.40, 4.4.8 and 5.0.8 maintenance versions were released. Meanwhile, the updated Security component removed the anonymous concept and a new Runtime component was proposed to decouple applications from global state. Finally, a new online conference in French was announced for May 7th 2020.

Symfony development highlights

This week, 31 pull requests were merged (25 in code and 6 in docs) and 18 issues were closed (16 in code and 2 in docs). Excluding merges, 19 authors made 854 additions and 359 deletions. See details for code and docs.

3.4 changelog:

  • f7749c3: [PhpUnitBridge] fixed compat with PHP 5.3
  • d765a09: fixed Form annotation
  • aee10cd: [Validator] fixed lazy property usage

4.4 changelog:

  • f8d3b06: [Cache] fixed not supported Redis eviction policies
  • 4528c11: [Serializer] do not transform empty \Traversable to Array
  • a804333: [Form] provide a useful message when extension types don't match

Master changelog:

  • 75e3d75: [DependencyInjection] limit recursivity of ResolveNoPreloadPass
  • a114f8d: [Security] require entry_point to be configured with multiple authenticators
  • 27c10f0: [HttpFoundation, HttpKernel] added more preload always-needed symbols
  • 0633308: [FrameworkBundle] append files to preload in CacheWarmupCommand
  • da6620c: [Notifier] fixed some Mattermost bridge errors
  • ed1b6ea: [Messenger] added missing port SQS Host Header request
  • c30d6f9: [Security] fixed bug introduced in entry_point configuration
  • 1308dd5: [Security] renamed VerifyAuthenticatorCredentialsEvent to CheckPassportEvent
  • 28bb74c: [SecurityBundle] fixed entry point service ID resolving and multiple guard entry points
  • 09f9079: [Security] removed anonymous in the new security system

Newest issues and pull requests

They talked about us

Call to Action


Sponsor the Symfony project.

New in Symfony 5.1: Async AWS Support

$
0
0
Jérémy DerusséTobias Nyholm

Contributed by
Jérémy Derussé and Tobias Nyholm
in #35992 and #36094.

The official AWS SDK for PHP simplifies the integration of Amazon AWS services (Amazon S3, Amazon DynamoDB, etc.) in your PHP applications. This SDK is feature complete, providing support for more than 200 AWS services (via 8,000 methods).

The Async AWS project is an unofficial reimagination of the AWS SDK. If provides support only for the most used services (7 vs 200 in the official SDK) and it's split into multiple small packages (adding S3 support in your app requires 0.6 MiB vs the 22 MiB required by the official SDK).

However, the biggest difference is that in Async AWS, all API calls are asynchronous by default (thanks to the underlying Symfony HTTP Client used by the project).

Thanks to the recent work made by Tobias Nyholm and Jérémy Derussé (15 weeks, 500 pull requests and tens of thousands of lines of code), Async AWS has recently tagged its 1.0.0 stable version. In Symfony 5.1 we decided to start using Async AWS by default in some components.

In the Mailer component, we've deprecated the SesApiTransport andSesHttpTransport classes in favor of SesApiAsyncAwsTransport andSesHttpAsyncAwsTransport, which are created when installing the following package:

1
$ composer require async-aws/ses

In addition to removing the complexity of signing requests, this change adds the following features:

  • Authentication via .aws/config.ini, Instance profile and WebIdentity (K8S service account);
  • Uses Signature V4 (the one recommended by the official SDK);
  • Full compatibility with the official API (it uses the official AWS SDK interface contract to generate classes).

Similarly, the Messenger component has been updated to use Async AWS when using Amazon SQS service. This removes most of the authentication/streaming complexity and keeps using the Symfony HttpClient integration.


Sponsor the Symfony project.

New in Symfony 5.1: Simpler Request Context

$
0
0
Nicolas Grekas

Contributed by
Nicolas Grekas
in #36651.

Generating URLs in console commands and any other places outside of the web context is challenging because Symfony doesn't have access to the current host, the base URL, etc.

The solution is to configure the request context using container parameters such as router.request_context.host. In Symfony 5.1 we've already improved this allowing you to configure these values via the framework.router option. However, we kept working on this feature to simplify it even more.

That's why in Symfony 5.1, you'll be able to configure the entire request context using a single default_uri parameter, instead of having to define several parameters:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Beforeframework:router:host:'example.org'scheme:'https'base_url:'my/path'# Afterframework:router:default_uri:'https://example.org/my/path/'

Related to this, in the pull request #36681, we've updated the assets config to reuse the router context by default. This means that most of the times, defining the default_uri option is enough to configure both the request context and the assets context.


Sponsor the Symfony project.

Symfony 5.1.0-BETA1 released

$
0
0

Symfony 5.1.0-BETA1 has just been released. Here is a list of the most important changes:

  • feature #36711 [Form] deprecate NumberToLocalizedStringTransformer::ROUN _ constants (@nicolas-grekas)
  • feature #36681 [FrameworkBundle] use the router context by default for assets (@nicolas-grekas)
  • feature #35545 [Serializer] Allow to include the severity in ConstraintViolationList (@dunglas)
  • feature #36471 [String] allow passing a string of custom characters to ByteString::fromRandom (@azjezz)
  • feature #35092 [Inflector][String] Move Inflector in String (@fancyweb)
  • feature #36302 [Form] Add the html5 option to ColorType to validate the input (@fancyweb)
  • feature #36184 [FrameworkBundle] Deprecate renderView() in favor of renderTemplate() (@javiereguiluz)
  • feature #36655 Automatically provide Messenger Doctrine schema to "diff" (@weaverryan)
  • feature #35849 [ExpressionLanguage] Added expression language syntax validator (@Andrej-in-ua)
  • feature #36656 [Security/Core] Add CustomUserMessageAccountStatusException (@VincentLanglet)
  • feature #36621 Log deprecations on a dedicated Monolog channel (@l-vo)
  • feature #34813 [Yaml] support YAML 1.2 octal notation, deprecate YAML 1.1 one (@xabbuh)
  • feature #36557 [Messenger] Add support for RecoverableException (@jderusse)
  • feature #36470 [DependencyInjection] Add a mechanism to deprecate public services to private (@fancyweb)
  • feature #36651 [FrameworkBundle] Allow configuring the default base URI with a DSN (@nicolas-grekas)
  • feature #36600 [Security] Added LDAP support to Authenticator system (@wouterj)
  • feature #35453 [Messenger] Add option to stop the worker after a message failed (@micheh)
  • feature #36094 [AmazonSqsMessenger] Use AsyncAws to handle SQS communication (@jderusse)
  • feature #36636 Add support of PHP8 static return type for withers (@l-vo)
  • feature #36586 [DI] allow loading and dumping tags with an attribute named "name" (@nicolas-grekas)
  • feature #36599 [HttpKernel] make kernels implementing WarmableInterface be part of the cache warmup stage (@nicolas-grekas)
  • feature #35992 [Mailer] Use AsyncAws to handle SES requests (@jderusse)
  • feature #36574 [Security] Removed anonymous in the new security system (@wouterj)
  • feature #36666 [Security] Renamed VerifyAuthenticatorCredentialsEvent to CheckPassportEvent (@wouterj)
  • feature #36575 [Security] Require entr _point to be configured with multiple authenticators (@wouterj)
  • feature #36570 [Security] Integrated Guards with the Authenticator system (@wouterj)
  • feature #36562 Revert "feature #30501 [FrameworkBundle][Routing] added Configurators to handle template and redirect controllers (HeahDude)" (@nicolas-grekas)
  • feature #36373 [DI] add syntax to stack decorators (@nicolas-grekas)
  • feature #36545 [DI] fix definition and usage of AbstractArgument (@nicolas-grekas)
  • feature #28744 [Serializer] Add an @Ignore annotation (@dunglas)
  • feature #36456 [String] Add locale-sensitive map for slugging symbols (@lmasforne)
  • feature #36535 [DI] skip preloading dependencies of non-preloaded services (@nicolas-grekas)
  • feature #36525 Improve SQS interoperability (@jderusse)
  • feature #36516 [Notifier] Throw an exception when the Slack DSN is not valid (@fabpot)
  • feature #35690 [Notifier] Add Free Mobile notifier (@noniagriconomie)
  • feature #33558 [Security] AuthenticatorManager to make "authenticators" first-class security (@wouterj)
  • feature #36187 [Routing] Deal with hosts per locale (@odolbeau)
  • feature #36464 [RedisMessengerBridge] Add a delet _afte _ack option (@Seldaek)
  • feature #36431 [Messenger] Add FIFO support to the SQS transport (@cv65kr)
  • feature #36455 [Cache] Added context to log messages (@Nyholm)
  • feature #34363 [HttpFoundation] Add InputBag (@azjezz)
  • feature #36445 [WebProfilerBundle] Make a difference between queued and sent emails (@fabpot)
  • feature #36424 [Mailer][Messenger] add return statement for MessageHandler (@ottaviano)
  • feature #36426 [Form] Deprecated unused old ServerParams util (@HeahDude)
  • feature #36433 [Console] cursor tweaks (@fabpot)
  • feature #35828 [Notifier][Slack] Send messages using Incoming Webhooks (@birkof, @fabpot)
  • feature #27444 [Console] Add Cursor class to control the cursor in the terminal (@pierredup)
  • feature #31390 [Serializer] UnwrappingDenormalizer (@nonanerz)
  • feature #36390 [DI] remove restriction and allow mixing "parent" and instanceof-conditionals/defaults/bindings (@nicolas-grekas)
  • feature #36388 [DI] deprecate the inline() function from the PHP-DSL in favor of service() (@nicolas-grekas)
  • feature #36389 [DI] allow decorators to reference their decorated service using the special .inner id (@nicolas-grekas)
  • feature #36345 [OptionsResolver] Improve the deprecation feature by handling package and version (@atailouloute)
  • feature #36372 [VarCloner] Cut Logger in dump (@lyrixx)
  • feature #35748 [HttpFoundation] Add support for all core response http control directives (@azjezz)
  • feature #36270 [FrameworkBundle] Add file links to named controllers in debug:router (@chalasr)
  • feature #35762 [Asset] Allows to download asset manifest over HTTP (@GromNaN)
  • feature #36195 [DI] add tags container.preload/.n _preload to declare extra classes to preload/services to not preload (@nicolas-grekas)
  • feature #36209 [HttpKernel] allow cache warmers to add to the list of preloaded classes and files (@nicolas-grekas)
  • feature #36243 [Security] Refactor logout listener to dispatch an event instead (@wouterj)
  • feature #36185 [Messenger] Add a Throwable argument in RetryStrategyInterface methods (@Benjamin Dos Santos)
  • feature #35871 [Config] Improve the deprecation features by handling package and version (@atailouloute)
  • feature #35879 [DependencyInjection] Deprecate ContainerInterface aliases (@fancyweb)
  • feature #36273 [FrameworkBundle] Deprecate flashbag and attributebag services (@William Arslett)
  • feature #36257 [HttpKernel] Deprecate single-colon notation for controllers (@chalasr)
  • feature #35778 [DI] Improve the deprecation features by handling package and version (@atailouloute)
  • feature #36129 [HttpFoundation][HttpKernel][Security] Improve UnexpectedSessionUsageException backtrace (@mtarld)
  • feature #36186 [FrameworkBundle] Dump kernel extension configuration (@guillbdx)
  • feature #34984 [Form] Allowing plural message on extra data validation failure (@popnikos)
  • feature #36154 [Notifier][Slack] Add fields on Slack Section block (@birkof)
  • feature #36148 [Mailer][Mailgun] Support more headers (@Nyholm)
  • feature #36144 [FrameworkBundle][Routing] Add link to source to router:match (@l-vo)
  • feature #36117 [PropertyAccess][DX] Added an UninitializedPropertyException (@HeahDude)
  • feature #36088 [Form] Added "collectio _entry" block prefix to CollectionType entries (@HeahDude)
  • feature #35936 [String] Add AbstractString::containsAny() (@nicolas-grekas)
  • feature #35744 [Validator] Add AtLeastOne constraint and validator (@przemyslaw-bogusz)
  • feature #35729 [Form] Correctly round model with PercentType and add a roundin _mode option (@VincentLanglet)
  • feature #35733 [Form] Added a "choic _filter" option to ChoiceType (@HeahDude)
  • feature #36003 [ErrorHandler][FrameworkBundle] better error messages in failing tests (@guillbdx)
  • feature #36034 [PhpUnitBridge] Deprecate @expectedDeprecation annotation (@hkdobrev)
  • feature #35924 [HttpClient] make HttpClient::create() return an AmpHttpClient when amphp/http-client is found but curl is not or too old (@nicolas-grekas)
  • feature #36072 [SecurityBundle] Added XSD for the extension configuration (@HeahDude)
  • feature #36074 [Uid] add AbstractUid and interop with base-58/32/RFC4122 encodings (@nicolas-grekas)
  • feature #36066 [Uid] use one class per type of UUID (@nicolas-grekas)
  • feature #36042 [Uid] add support for Ulid (@nicolas-grekas)
  • feature #35995 [FrameworkBundle] add --deprecations on debug:container command (@Simperfit, @noemi-salaun)
  • feature #36059 [String] leverage Stringable from PHP 8 (@nicolas-grekas)
  • feature #35940 [UID] Added the component + Added support for UUID (@lyrixx)
  • feature #31375 [Form] Add labe _html attribute (@przemyslaw-bogusz)
  • feature #35997 [DX][Testing] Added a loginUser() method to test protected resources (@javiereguiluz, @wouterj)
  • feature #35978 [Messenger] Show message & handler(s) class description in debug:messenger (@ogizanagi)
  • feature #35960 [Security/Http] Hash Persistent RememberMe token (@guillbdx)
  • feature #35115 [HttpClient] Add portable HTTP/2 implementation based on Amp's HTTP client (@nicolas-grekas)
  • feature #35913 [LDAP] Add error code in exceptions generated by ldap (@Victor Garcia)
  • feature #35782 [Routing] Add stateless route attribute (@mtarld)
  • feature #35732 [FrameworkBundle][HttpKernel] Add session usage reporting in stateless mode (@mtarld)
  • feature #35815 [Validator] Allow Sequentially constraints on classes + target guards (@ogizanagi)
  • feature #35747 [Routing][FrameworkBundle] Allow using env() in route conditions (@atailouloute)
  • feature #35857 [Routing] deprecate RouteCompiler::REGE _DELIMITER (@nicolas-grekas)
  • feature #35804 [HttpFoundation] Added MarshallingSessionHandler (@atailouloute)
  • feature #35858 [Security] Deprecated ROL _PREVIOU _ADMIN (@wouterj)
  • feature #35848 [Validator] add alpha3 option to Language constraint (@xabbuh)
  • feature #31189 [Security] Add I _IMPERSONATOR, I _ANONYMOUS and I _REMEMBERED (@HeahDude)
  • feature #30994 [Form] Added support for caching choice lists based on options (@HeahDude)
  • feature #35783 [Validator] Add the divisibleBy option to the Count constraint (@fancyweb)
  • feature #35649 [String] Allow to keep the last word when truncating a text (@franmomu)
  • feature #34654 [Notifier] added Sinch texter transport (@imiroslavov)
  • feature #35673 [Process] Add getter for process starttime (@dompie)
  • feature #35689 [String] Transliterate & to and (@Warxcell)
  • feature #34550 [Form] Added an AbstractChoiceLoader to simplify implementations and handle global optimizations (@HeahDude)
  • feature #35688 [Notifier] Simplify OVH implementation (@fabpot)
  • feature #34540 [Notifier] add OvhCloud bridge (@antiseptikk)
  • feature #35192 [PhpUnitBridge] Add the ability to expect a deprecation inside a test (@fancyweb)
  • feature #35667 [DomCrawler] Rename UriExpander.php -> UriResolver (@lyrixx)
  • feature #35611 [Console] Moved estimated & remaining calculation logic to separate get method (@peterjaap)
  • feature #33968 [Notifier] Add Firebase bridge (@Jeroeny)
  • feature #34022 [Notifier] add RocketChat bridge (@Jeroeny)
  • feature #32454 [Messenger] Add SQS transport (@jderusse)
  • feature #33875 Add Mattermost notifier bridge (@thePanz)
  • feature #35400 [RFC][DX][OptionsResolver] Allow setting info message per option (@yceruto)
  • feature #30501 [FrameworkBundle][Routing] added Configurators to handle template and redirect controllers (@HeahDude)
  • feature #35373 [Translation] Support name attribute on the xliff2 translator loader (@Taluu)
  • feature #35550 Leverage trigge _deprecation() from symfony/deprecation-contracts (@nicolas-grekas)
  • feature #35648 [Contracts/Deprecation] don't use assert(), rename to trigge _deprecation() (@nicolas-grekas)
  • feature #33456 [MonologBridge] Add Mailer handler (@BoShurik)
  • feature #35384 [Messenger] Add receiving of old pending messages (redis) (@toooni)
  • feature #34456 [Validator] Add a constraint to sequentially validate a set of constraints (@ogizanagi)
  • feature #34334 [Validator] Allow to define a reusable set of constraints (@ogizanagi)
  • feature #35642 [HttpFoundation] Make dependency on Mime component optional (@atailouloute)
  • feature #35635 [HttpKernel] Make ErrorListener unaware of the event dispatcher (@derrabus)
  • feature #35019 [Cache] add SodiumMarshaller (@atailouloute)
  • feature #35625 [String] Add the s() helper method (@fancyweb)
  • feature #35624 [String] Remove the @experimental status (@fancyweb)
  • feature #33848 [OptionsResolver] Add new OptionConfigurator class to define options with fluent interface (@lmillucci, @yceruto)
  • feature #35076 [DI] added possibility to define services with abstract arguments (@Islam93)
  • feature #35608 [Routing] add priority option to annotated routes (@nicolas-grekas)
  • feature #35526 [Contracts/Deprecation] Provide a generic function and convention to trigger deprecation notices (@nicolas-grekas)
  • feature #32747 [Form] Add "is empty callback" to form config (@fancyweb)
  • feature #34884 [DI] Enable auto alias compiler pass by default (@X-Coder264)
  • feature #35596 [Serializer] Add support for stdClass (@dunglas)
  • feature #34278 Update bootstra _ _layout.html.twig (@CoalaJoe)
  • feature #31309 [SecurityBundle] add "service" option in remembe _me firewall (@Pchol)
  • feature #31429 [Messenger] add support for abstract handlers (@timiTao)
  • feature #31466 [Validator] add Validation::createCallable() (@janvernieuwe)
  • feature #34747 [Notifier] Added possibility to extract path from provided DSN (@espectrio)
  • feature #35534 [FrameworkBundle] Use MailerAssertionsTrait in KernelTestCase (@adrienfr)
  • feature #35590 [FrameworkBundle] use framework.translator.enable _locales to build routes' default _locale" requirement (@nicolas-grekas)
  • feature #35167 [Notifier] Remove superfluous parameters in Message::fromNotification() (@fancyweb)
  • feature #35415 Extracted code to expand an URI to UriExpander (@lyrixx)
  • feature #35485 [Messenger] Add support for PostgreSQL LISTEN/NOTIFY (@dunglas)
  • feature #32039 [Cache] Add couchbase cache adapter (@ajcerezo)
  • feature #32433 [Translation] Introduce a way to configure the enabled locales (@javiereguiluz)
  • feature #33003 [Filesystem] Add $suffix argument to tempnam() (@jdufresne)
  • feature #35347 [VarDumper] Add a RdKafka caster (@romainneutron)
  • feature #34925 Messenger: validate options for AMQP and Redis Connections (@nikophil)
  • feature #33315 [WebProfiler] Improve HttpClient Panel (@ismail1432)
  • feature #34298 [String] add LazyString to provide memoizing stringable objects (@nicolas-grekas)
  • feature #35368 [Yaml] Deprecate using the object and const tag without a value (@fancyweb)
  • feature #35566 [HttpClient] adding NoPrivateNetworkHttpClient decorator (@hallboav)
  • feature #35560 [HttpKernel] allow using public aliases to reference controllers (@nicolas-grekas)
  • feature #34871 [HttpClient] Allow pass array of callable to the mocking http client (@Koc)
  • feature #30704 [PropertyInfo] Add accessor and mutator extractor interface and implementation on reflection (@joelwurtz, @Korbeil)
  • feature #35525 [Mailer] Randomize the first transport used by the RoundRobin transport (@fabpot)
  • feature #35116 [Validator] Add alpha3 option to country constraint (@maxperrimond)
  • feature #29139 [FrameworkBundle][TranslationDebug] Return non-zero exit code on failure (@DAcodedBEAT)
  • feature #35050 [Mailer] added tag/metadata support (@kbond)
  • feature #35215 [HttpFoundation] added withers to Cookie class (@ns3777k)
  • feature #35514 [DI][Routing] add wither to configure the path of PHP-DSL configurators (@nicolas-grekas)
  • feature #35519 [Mailer] Make default factories public (@fabpot)
  • feature #35156 [String] Made AbstractString::width() follow POSIX.1-2001 (@fancyweb)
  • feature #35308 [Dotenv] Add Dotenv::bootEnv() to check for .env.local.php before calling Dotenv::loadEnv() (@nicolas-grekas)
  • feature #35271 [PHPUnitBridge] Improved deprecations display (@greg0ire)
  • feature #35478 [Console] Add constants for main exit codes (@Chi-teck)
  • feature #35503 [Messenger] Add TLS option to Redis transport's DSN (@Nyholm)
  • feature #35262 [Mailer] add ability to disable the TLS peer verification via DSN (@Aurélien Fontaine)
  • feature #35194 [Mailer] read default timeout from ini configurations (@azjezz)
  • feature #35422 [Messenger] Move Transports to separate packages (@Nyholm)
  • feature #35425 [CssSelector] Added cache on top of CssSelectorConverter (@lyrixx)
  • feature #35362 [Cache] Add LRU + max-lifetime capabilities to ArrayCache (@nicolas-grekas)
  • feature #35402 [Console] Set Command::setHidden() final for adding default param in SF 6.0 (@lyrixx)
  • feature #35407 [HttpClient] collect the body of responses when possible (@nicolas-grekas)
  • feature #35391 [WebProfilerBundle][HttpClient] Added profiler links in the Web Profiler -> Http Client panel (@cristagu)
  • feature #35295 [Messenger] Messenger redis local sock dsn (@JJarrie)
  • feature #35322 [Workflow] Added a way to not fire the announce event (@lyrixx)
  • feature #35321 [Workflow] Make many internal services as hidden (@lyrixx)
  • feature #35235 [Serializer] Added scalar denormalization (@a-menshchikov)
  • feature #35310 [FrameworkBundle] Deprecate not setting the "framework.router.utf8" option (@nicolas-grekas)
  • feature #34387 [Yaml] Added yaml-lint binary (@jschaedl)
  • feature #35257 [FrameworkBundle] TemplateController should accept extra arguments to be sent to the template (@Benjamin RICHARD)
  • feature #34980 [Messenger] remove several messages with command messenger:failed:remove (@nikophil)
  • feature #35298 Make sure the UriSigner can be autowired (@Toflar)
  • feature #31518 [Validator] Added HostnameValidator (@karser)
  • feature #35284 Simplify UriSigner when working with HttpFoundation's Request (@Toflar)
  • feature #35285 [FrameworkBundle] Adding better output to secrets:decrypt-to-local command (@weaverryan)
  • feature #35273 [HttpClient] Add LoggerAwareInterface to ScopingHttpClient and TraceableHttpClient (@pierredup)
  • feature #34865 [FrameworkBundle][ContainerLintCommand] Style messages (@fancyweb)
  • feature #34847 Add support for safe HTTP preference - RFC 8674 (@pyrech)
  • feature #34880 [Twig][Form] Twig theme for Foundation 6 (@Lyssal)
  • feature #35281 [FrameworkBundle] Configure RequestContext through router config (@benji07)
  • feature #34819 [Console] Add SingleCommandApplication to ease creation of Single Command Application (@lyrixx)
  • feature #35104 [Messenger] Log sender alias in SendMessageMiddleware (@ruudk)
  • feature #35205 [Form] derive the view timezone from the model timezone (@xabbuh)
  • feature #34986 [Form] Added default inputmode attribute to Search, Email and Tel form types (@fre5h)
  • feature #35091 [String] Add the reverse() method (@fancyweb)
  • feature #35029 [DI] allow "." and "-" in env processor lines (@nicolas-grekas)
  • feature #34548 Added access decision strategy to respect voter priority (@aschempp)
  • feature #34881 [FrameworkBundle] Allow using the kernel as a registry of controllers and service factories (@nicolas-grekas)
  • feature #34977 [EventDispatcher] Deprecate LegacyEventDispatcherProxy (@derrabus)
  • feature #34873 [FrameworkBundle] Allow using a ContainerConfigurator in MicroKernelTrait::configureContainer() (@nicolas-grekas)
  • feature #34872 [FrameworkBundle] Added flex-compatible default implementations for MicroKernelTrait::registerBundles() and getProjectDir() (@nicolas-grekas)
  • feature #34916 [DI] Add support for defining method calls in InlineServiceConfigurator (@Lctrs)
  • feature #31889 [Lock] add mongodb store (@kralos)
  • feature #34924 [ErrorHandler] Enabled the dark theme for exception pages (@javiereguiluz)
  • feature #34769 [DependencyInjection] Autowire public typed properties (@Plopix)
  • feature #34856 [Validator] mark the Composite constraint as internal (@xabbuh)
  • feature #34771 Deprecate Response::create() methods (@fabpot)
  • feature #32388 [Form] Allow to translate each language into its language in LanguageType (@javiereguiluz)
  • feature #34119 [Mime] Added MimeType for "msg" (@LIBERT Jérémy)
  • feature #34648 [Mailer] Allow to configure or disable the message bus to use (@ogizanagi)
  • feature #34705 [Validator] Label regex in date validator (@kristofvc)
  • feature #34591 [Workflow] Added Registry::has() to check if a workflow exists (@lyrixx)
  • feature #32937 [Routing] Deprecate RouteCollectionBuilder (@vudaltsov)
  • feature #34557 [PropertyInfo] Add support for typed properties (PHP 7.4) (@dunglas)
  • feature #34573 [DX] [Workflow] Added a way to specify a message when blocking a transition + better default message in case it is not set (@lyrixx)
  • feature #34457 Added context to exceptions thrown in apply method (@koenreiniers)

Want to upgrade to this new release? Because Symfony protects backwards-compatibility very closely, this should be quite easy. UseSymfonyInsight upgrade reports to detect the code you will need to change in your project andread our upgrade documentation to learn more.

Want to be notified whenever a new Symfony release is published? Or when a version is not maintained anymore? Or only when a security issue is fixed? Consider subscribing to the Symfony Roadmap Notifications.


Sponsor the Symfony project.

New in Symfony 5.1: ExpressionLanguage validator

$
0
0
Andrey Sevastianov

Contributed by
Andrey Sevastianov
in #35849.

The ExpressionLanguage component provides an engine to compile and evaluate expressions. It's used by many companies to allow non-developers write business rules (e.g. evaluate the following expression to decide if your store offers a discount: 'user["isActive"] == true and product["price"] > 20').

In Symfony 5.1 we've improved the ExpressionLanguage component to allowvalidating the expressions without parsing or evaluating them. TheExpressionLanguage and Parser classes now include a lint() method to validate expressions:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
useSymfony\Component\ExpressionLanguage\Lexer;useSymfony\Component\ExpressionLanguage\Parser;$lexer=newLexer();$parser=newParser([]);$parser->lint($lexer->tokenize($expression),$allowedVariableNames);$expression='foo["some_key"].callFunction(a ? b)';$allowedVariableNames=['foo','a','b'];// Result: no error; expression is valid.$expression='foo["some_key")';$allowedVariableNames=['foo'];// Result: Unclosed "[" around position 3 for expression `foo["some_key")`.$expression='{key: foo key2: bar}';$allowedVariableNames=['foo','bar'];// Result: A hash value must be followed by a comma//         Unexpected token "name" of value "key2" ("punctuation" expected with value ",")//         around position 11 for expression `{key: foo key2: bar}`.

In addition to using these lint() methods, you can also use the newExpressionLanguageSyntax constraint to validate that the value stored in some property defines valid ExpressionLanguage syntax (you can optionally validate the expression variable names too):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
namespaceApp\Entity;useSymfony\Component\Validator\ConstraintsasAssert;classOrder{/**     * @Assert\ExpressionLanguageSyntax()     */protected$promotion;/**     * @Assert\ExpressionLanguageSyntax(     *     names = ['user', 'shipping_centers'],     *     validateNames = true     * )     */protected$shippingOptions;}

Sponsor the Symfony project.

New in SymfonyInsight: printable Upgrade reports

$
0
0

One of the core features of SymfonyInsight is its ability to help you maintain your project up to date with new versions of your dependencies.

We do this by analyzing your project on each of your commits, in order to find the spots where you are using deprecated features from installed packages. We then gather all these results in a detailed Upgrade report that helps you remove these deprecations and safely upgrade your dependencies.

Earlier today, we released a new feature related to upgrading: printable upgrade reports. In addition to printable maintenance reports, you can now also print Upgrade reports, giving you an easy way to communicate with your colleagues and customers about what needs to be done to keep your project up to date.

SymfonyInsight upgrade reports

And as always, if you have any issue, feel free to contact us at the support!

Enjoy!


Sponsor the Symfony project.

New in Symfony 5.1: Server-side request forgery protection

$
0
0
Hallison Boaventura

Contributed by
Hallison Boaventura
in #35566.

Security vulnerabilities such as CSRF (Cross-site request forgery) are well known by most web developers and Symfony provides automatic protection against them. A related but lesser known vulnerability is called SSRF (Server-side request forgery).

SSRF allows an attacker to induce the backend application to make HTTP requests to an arbitrary domain. These attacks can also target the internal hosts and IPs of the attacked server. The following simplified example has been extracted fromthis article, which explains the problem in detail:

Step 1: Your backend admin is freely accessible but only from internal IPs (e.g. https://192.168.0.68/admin).

Step 2: Your web application makes API requests like the following to get certain information (e.g. the stock of a product):

1
2
3
4
5
POST /product/stock HTTP/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 118

stockApi=https://stock.weliketoshop.net:8080/product/stock/check%3FproductId%3D6%26storeId%3D1

Step 3: The attacker can submit the following request to access to your backend admin:

1
2
3
4
5
POST /product/stock HTTP/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 118

stockApi=https://192.168.0.68/admin

The solution, as it happens with many security vulnerabilities, requires filtering the user input (in this case, the IP address requested by the user). In Symfony 5.1, we improved the HttpClient component to add a newNoPrivateNetworkHttpClient that blocks all internal IP addresses by default.

This new client decorates the default HttpClient, so you can use it as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
useSymfony\Component\HttpClient\HttpClient;useSymfony\Component\HttpClient\NoPrivateNetworkHttpClient;$client=newNoPrivateNetworkHttpClient(HttpClient::create());// nothing changes when requesting public networks$client->request('GET','https://example.com/');// however, all requests to private networks are now blocked by default$client->request('GET','http://localhost/');// the second optional argument defines the networks to block// in this example, requests from 104.26.14.0 to 104.26.15.255 will result in an exception// but all the other requests, including other internal networks, will be allowed$client=newNoPrivateNetworkHttpClient(HttpClient::create(),['104.26.14.0/23']);

Sponsor the Symfony project.

A Week of Symfony #697 (4-10 May 2020)

$
0
0

This week, Symfony released the first beta of Symfony 5.1.0, the upcoming version which will be released at the end of May 2020. Meanwhile, Symfony added a new mechanism to deprecate public services into private, a new way to automate the handling of schema differences and deprecated the Inflector component in favor of the String component.

Symfony development highlights

This week, 75 pull requests were merged (69 in code and 6 in docs) and 57 issues were closed (47 in code and 10 in docs). Excluding merges, 26 authors made 6,234 additions and 1,744 deletions. See details for code and docs.

3.4 changelog:

  • e3d2a50: [Inflector] improve testSingularize() argument name
  • 469d82d: [Validator] s469d82d6e2b9af282690482edcdd03a2be4de377kip validation when email is an empty object
  • bb77914: [Yaml] fixed parse error when unindented collections contain a comment
  • 78a7f46: [DX] show the ParseException message in all YAML file loaders
  • cf0d086: [WebProfiler] do not add src-elem CSP directives if they do not exist
  • bd952b9: [Filesystem] handle paths on different drives
  • cfa048c: fixed exception messages containing exception messages
  • 6340e87: [Yaml] prevent notice for invalid octal numbers on PHP 7.4
  • 9b89115: [PhpUnitBridge] mark parent class also covered in CoverageListener
  • 9b088bb: removed patches for Doctrine bugs and deprecations
  • 94482fe: [FrameworkBundle] display actual target for error in AssetsInstallCommand
  • f6ae18e: [DependencyInjection, EventDispatcher] added contract for implementation

4.4 changelog:

  • 0a7fa8f: executed Docker dependent tests with GitHub actions
  • 64e5a9d: [Console] default hidden question to 1 attempt for non-tty session
  • cf6e499: [Console] don't check tty on stdin because it breaks with data lost during stream conversion
  • a609375: [Mime] fixed bad method call on EmailAddressContains
  • e75c227: [Messenger] queue name is a required parameter
  • 99d5818: [HttpClient] test that timeout is not fatal
  • 6310084: [Mime] handle passing custom mime types as string

Master changelog:

  • e9be741: [FrameworkBundle] allow configuring the default base URI with a DSN
  • a910192: [DependencyInjection] add a mechanism to deprecate public services to private
  • 6852327: [Yaml] properly handle empty lines
  • 0d4bba8: [Messenger] added support for RecoverableException
  • 09d78cf: [Yaml] added support for YAML 1.2 octal notation and deprecated YAML 1.1 one
  • 55706f7: log deprecations on a dedicated Monolog channel
  • a0c2dd8: [Security] added CustomUserMessageAccountStatusException
  • 3d30ff7: [ExpressionLanguage] added expression language syntax validator
  • b9d4149: automatically provide Messenger Doctrine schema to "diff"
  • 341ea45: [Form] added the html5 option to ColorType to validate the input
  • 3e737ec: [Inflector, String] moved Inflector to String
  • 5a2aef1: [String] allow passing a string of custom characters to ByteString::fromRandom
  • 3cb4056: [Serializer] allowed to include the severity in ConstraintViolationList
  • 36c0ce7: [FrameworkBundle] use the router context by default for assets
  • 4dbf987: [Form] deprecated NumberToLocalizedStringTransformer::ROUND_* constants
  • af160e2: [HttpFoundation] fixed perf of ResponseHeaderBag::initDate()
  • 75e71e3: [FrameworkBundle] removed getProjectDir method from MicroKernelTrait
  • 4eb32cf: [DependencyInjection] reduced recursivity of ResolveHotPathPass
  • 070552e: [DependencyInjection] give priority to container.hot_path over container.no_preload
  • 8f58a2d: [Cache] fixed accepting sub-second max-lifetimes in ArrayAdapter
  • 012247d: [HttpClient] removed "experimental" annotations
  • 8fec065: [HttpClient] fixed dealing with informational response
  • 97a5782: [Security] improved method signatures
  • 3acc28f: [HttpClient] added TimeoutExceptionInterface

Symfony CLI

Symfony CLI is a must-have tool when developing Symfony applications on your local machine. It includes theSymfony Local Server, the best way to run local Symfony applications. This week Symfony CLI released its new 4.14.4 version with the following changes:

  • Hide cursor when the spinner is running
  • Fix errors not displayed when starting the proxy
  • Fix detaching domains
  • Fix 'panic: send on closed channel'

Newest issues and pull requests

They talked about us

Call to Action


Sponsor the Symfony project.

New in Symfony 5.1: Deprecate public services into private services

$
0
0
Thomas Calvet

Contributed by
Thomas Calvet
in #36470.

One of the key features that makes developers love Symfony is the handling of deprecated features. Symfony's backward compatibility promise ("BC promise") ensures that your application will never break when upgrading between minor versions.

In Symfony 5.1 we introduced a new way to deprecate public services and turn them into private while keeping that BC promise.

In practice, this features require adding a service tag calledcontainer.private and a couple of tag attributes that define the package and version where it was deprecated:

1
2
3
4
5
6
services:foo:# ...public:truetags:-{ name:'container.private', package:'foo/bar','version':'1.2'}

If your application tries to get that service directly from the container ($container->get('foo')) you'll see the following error:

1
2
Since foo/bar 1.2: Accessing the "foo" service directly from the container
is deprecated, use dependency injection instead.

Technically this feature uses a compiler pass to create a deprecated public alias of the public service. This is done only when the code access the service directly (not when using autowiring) to avoid displaying unnecessary deprecations.

We're already using this feature in Symfony core to turn some public services into private (e.g. the twig service in PR #36739) and you can also start using it in your own public bundles and private applications.


Sponsor the Symfony project.

New in Symfony 5.1: Deprecated the Inflector component

$
0
0
Thomas Calvet

Contributed by
Thomas Calvet
in #35092.

Symfony Inflector component converts words between their singular and plural forms (for now, only in English). It's used in several parts of Symfony to generate singular property names from plural method names and viceversa ($foo<-> setFoos(), $foos<-> addFoo()).

In Symfony 5.1 we've deprecated this component and moved its logic into theString component, which provides the best experience to work with strings in PHP applications.

The new inflector is available via the EnglishInflector class (which reflects the intention to expand the inflector to other languages in the future). The interface remains the same:

1
2
3
4
5
6
7
8
9
namespaceSymfony\Component\String\Inflector;interfaceInflectorInterface{// the returned values are arrays because in some cases, there// are multiple valid singulars/plurals for a given wordpublicfunctionsingularize(string$plural):array;publicfunctionpluralize(string$singular):array;}

This is how you can use it in your applications:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
useSymfony\Component\String\Inflector\EnglishInflector;$inflector=newEnglishInflector();$result=$inflector->singularize('teeth');// ['tooth']$result=$inflector->singularize('radii');// ['radius']$result=$inflector->singularize('leaves');// ['leaf', 'leave', 'leaff']$result=$inflector->pluralize('bacterium');// ['bacteria']$result=$inflector->pluralize('news');// ['news']$result=$inflector->pluralize('person');// ['persons', 'people']

Sponsor the Symfony project.

New in Symfony 5.1: AtLeastOne validator

$
0
0
Przemysław Bogusz

Contributed by
Przemysław Bogusz
in #35744.

In addition to the Hostname validator and the ExpressionLanguage validator, in Symfony 5.1 we've added another validator called AtLeastOne. You can apply it to methods and properties to ensure that their values satisfies at least one of the given constraints (which can be any of the built-in Symfony constraints and/or your own custom constraints):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
namespaceApp\Entity;useSymfony\Component\Validator\ConstraintsasAssert;classSomeEntity{/**     * @Assert\AtLeastOne({     *     @Assert\Length(min=5),     *     @Assert\EqualTo("bar")     * })     */public$name='foo';/**     * @Assert\AtLeastOne({     *     @Assert\All({@Assert\GreaterThanOrEqual(10)}),     *     @Assert\Count(20)     * })     */public$numbers=['3','5'];/**     * @Assert\All({     *     @Assert\AtLeastOne({     *          @Assert\GreaterThanOrEqual(5),     *          @Assert\LessThanOrEqual(3)     *     })     * })     */public$otherNumbers=['4','5'];}

By default, the error messages lists all the failed conditions:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
name: This value should satisfy at least one of the following constraints:
[1] This value is too short. It should have 5 characters or more.
[2] This value should be equal to "bar".

numbers: This value should satisfy at least one of the following constraints:
[1] Each element of this collection should satisfy its own set of constraints.
[2] This collection should contain exactly 20 elements.

otherNumbers[0]: This value should satisfy at least one of the following constraints:
[1] This value should be greater than or equal to 5.
[2] This value should be less than or equal to 3.

Sponsor the Symfony project.

New in Symfony 5.1: Access decision based on voter priority

$
0
0
Andreas Schempp

Contributed by
Andreas Schempp
in #34548.

In Symfony applications, security voters centralize the authorization logic which decides if a given user can access to the requested resource. They are regular Symfony services tagged with the security.voter tag, so they can define their priorities via the priority attribute of the tag.

In practice this voter priority is mostly irrelevant, because of theaccess decision strategies used by Symfony:

  • affirmative, grants access as soon as there is one voter granting access;
  • consensus, grants access if there are more voters granting access than denying;
  • unanimous, grants access if there is no voter denying access.

That's why in Symfony 5.1 we've added a new access decision strategy calledpriority which grants or denies access depending on the first voter that does not abstain. In this case, the voter priority is essential, because the first non-abstain decision will be the final decision:

1
2
3
4
5
# config/packages/security.yamlsecurity:access_decision_manager:strategy:priority# ...

This feature originated from the Contao CMS project, which is built with Symfony, and defines some default permissions which other extensions/bundles must be able to override. This new priority access decision strategy is the only one able to do that.


Sponsor the Symfony project.

New in Symfony 5.1: OptionsResolver improvements

$
0
0

The OptionsResolver component helps you configure objects with option arrays. In Symfony 5.1 we've improved it with the following features.

Fluent Interface

Lorenzo Millucci

Contributed by
Lorenzo Millucci
in #33848.

It's common to configure several features for each option (its allowed types, its default values, whether it's required or not, etc.) Thanks to the newdefine() method, you can use a fluent interface to configure everything about an option without repeating its name in different methods:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Before$resolver->setRequired('host');$resolver->setDefaults(['host'=>'smtp.example.org']);$resolver->setAllowedTypes('host','string');// After$resolver->define('host')->required()->default('smtp.example.org')->allowedTypes('string');

Option Debug Information

Yonel Ceruto

Contributed by
Yonel Ceruto
in #35400.

Sometimes, the name of an option or its highly dynamic feature makes it hard to understand the error messages generated by Symfony. That's why in Symfony 5.1 we've introduced a new method which improves DX (developer experience) allowing you to add a description/help/debug message for the option.

Imagine that you define a datetime option whose value must be in the future:

1
2
3
$resolver->setAllowedValues('scheduledAt',staticfunction($value):bool{return$value>=new\DateTime('now');});

This is the standard error message displayed by Symfony in this case:

1
The option "scheduledAt" with value DateTime is invalid.

However, if you add the info() or setInfo() methods:

1
2
3
4
5
6
7
// using the traditional syntax$resolver->setInfo('scheduledAt','It must be a date in the future.');// using the fluent interface$resolver->define('scheduledAt')// ...->info('It must be a date in the future.');

The error message displayed now is:

1
2
The option "scheduledAt" with value DateTime is invalid.
Info: It must be a date in the future.

Sponsor the Symfony project.

Symfony 5.1.0-RC1 released

$
0
0

Symfony 5.1.0-RC1 has just been released. Here is a list of the most important changes:

  • bug #36832 [Security] Improved upgrade path for custom remember me services (@wouterj)
  • bug #36592 [BrowserKit] Allow Referer set by history to be overridden (@Slamdunk)
  • bug #36800 [DI] Renamed some PHP-DSL functions (@javiereguiluz)
  • bug #36806 RememberMeLogoutListener should depend on LogoutHandlerInterface (@scheb)
  • bug #36805 [SecurityCore] Fix NoopAuthenticationManager::authenticate() return value (@chalasr)
  • bug #36823 [HttpClient] fix PHP warning + accept status code >= 600 (@nicolas-grekas)
  • bug #36824 [Security/Core] fix compat of NativePasswordEncoder with pre-PHP74 values of PASSWOR _ consts (@nicolas-grekas)
  • bug #36811 [DependencyInjection] Fix register event listeners compiler pass (@X-Coder264)
  • bug #36789 Change priority of KernelEvents::RESPONSE subscriber (@marcw)
  • bug #36794 [Serializer] fix issue with PHP 8 (@nicolas-grekas)
  • bug #36786 [WebProfiler] Remove 'none' when appending CSP tokens (@ndench)
  • bug #36796 [DI] Use requir _once instead of require when appending cache warmer-returned files to preload file (@ovrflo)
  • bug #36743 [Yaml] Fix escaped quotes in quoted multi-line string (@ossinkine)
  • bug #36773 [HttpClient] preserve the identity of responses streamed by TraceableHttpClient (@nicolas-grekas)
  • bug #36777 [TwigBundle] FormExtension does not have a constructor anymore since sf 4.0 (@Tobion)
  • bug #36766 [HttpClient] add TimeoutExceptionInterface (@nicolas-grekas)
  • bug #36716 [Mime] handle passing custom mime types as string (@mcneely)
  • bug #36765 [HttpClient] fix dealing with informational response (@nicolas-grekas)
  • bug #36747 Queue name is a required parameter (@theravel)
  • bug #36751 [Mime] fix bad method call on EmailAddressContains (@Kocal)
  • bug #36737 [Cache] fix accepting sub-second max-lifetimes in ArrayAdapter (@nicolas-grekas)
  • bug #36749 [DI] give priority to container.ho _path over container.n _preload (@nicolas-grekas)
  • bug #36721 [FrameworkBundle] remove getProjectDir method from MicroKernelTrait (@garak)

Want to upgrade to this new release? Because Symfony protects backwards-compatibility very closely, this should be quite easy. UseSymfonyInsight upgrade reports to detect the code you will need to change in your project andread our upgrade documentation to learn more.

Want to be notified whenever a new Symfony release is published? Or when a version is not maintained anymore? Or only when a security issue is fixed? Consider subscribing to the Symfony Roadmap Notifications.


Sponsor the Symfony project.

A Week of Symfony #698 (11-17 May 2020)

$
0
0

This week, Symfony published the first release candidate version of Symfony 5.1 so you can test it in your projects before the final release. Meanwhile, the Symfony 5 book published its simplified Chinese translation.

Symfony development highlights

This week, 39 pull requests were merged (24 in code and 15 in docs) and 33 issues were closed (24 in code and 9 in docs). Excluding merges, 23 authors made 584 additions and 322 deletions. See details for code and docs.

3.4 changelog:

  • a8cb3cd: [Yaml] fixed escaped quotes in quoted multi-line string
  • 8f2c68f: [Serializer] fixed issue with PHP 8
  • 30e2543: [Security] update test to test AccountStatusException behavior
  • cec0dfe: [Translator] embed resource name in error message
  • cb7e78c: [BrowserKit] allow Referer set by history to be overridden

4.4 changelog:

  • b4342e3: [Messenger] missing description in messenger:setup-transports command
  • 3150104: [WebProfiler] removed 'none' when appending CSP tokens
  • ae67376: [DependencyInjection] fixed register event listeners compiler pass
  • bce3760: [Security] fixed compat of NativePasswordEncoder with pre-PHP74 values of PASSWORD_* consts
  • cc519aa: [HttpClient] fixed PHP warning + accept status code >= 600

5.1 changelog:

  • a53d126: [DependencyInjection] use require_once instead of require when appending cache warmer-returned files to preload file
  • fb80229: [String] move Inflector's polyfill-ctype dependency to String
  • a86058c: [Security] fixed NoopAuthenticationManager::authenticate() return value
  • 5dd99f2: [Security] RememberMeLogoutListener should depend on LogoutHandlerInterface
  • cf04f1e: [DependencyInjection] renamed some PHP-DSL functions
  • c268915: [Security] improved upgrade path for custom remember me services

Newest issues and pull requests

They talked about us

Call to Action


Sponsor the Symfony project.

New in Symfony 5.1: Validator improvements

$
0
0

In addition to the new AtLeastOneOf, ExpressionLanguageSyntax and Hostname validators, Symfony 5.1 introduced other validator improvements.

Added alpha3 option to Country

Maxime Perrimond

Contributed by
Maxime Perrimond
in #35116.

If you set the new alpha3 option to true in the Country constraint, the value is checked as a valid ISO 3166-1 alpha-3 three-letter country code (e.g. ARG = Argentina) instead of the default ISO 3166-1 alpha-2 two-letter country code (e.g. AR = Argentina).

Added alpha3 option to Language

Christian Flothmann

Contributed by
Christian Flothmann
in #35848.

Similar to the previous feature, in the Language constraint we added a newalpha3 option to allow using ISO 639-2 three-letter language codes (swe = Swedish) instead of the default ISO 639-1 two-letter language code (sv = Swedish).

Added divisibleBy option to Count

Thomas Calvet

Contributed by
Thomas Calvet
in #35783.

The new divisibleBy option added to the Count constraint checks that the the number of elements of the given collection is divisible by a certain number. If you need to perform this check in other values that aren't collections, use the DivisibleBy constraint.

Validation callables

janvernieuwe

Contributed by
janvernieuwe
in #31466.

Sometimes you need to reuse Symfony's constraints in places like the Symfony Console, to validate the answer to a console question. That's why we've added a new Validation::createCallable() to create a callable based on the given constraints:

1
2
3
4
5
6
7
8
useSymfony\Component\Console\Style\SymfonyStyle;useSymfony\Component\Validator\Constraints\NotNull;useSymfony\Component\Validator\Validation;$io=newSymfonyStyle($input,$output);$validation=Validation::createCallable(newNotBlank());$wsdl=$io->ask('Wsdl location URL',null,$validation);

The argument of createCallable() is variadic, so you can pass any number of constraints:

1
2
3
4
5
// ...useSymfony\Component\Validator\Constraints\Length;useSymfony\Component\Validator\Constraints\Url;$validation=Validation::createCallable(newLength(['max'=>255]),newUrl());

Sponsor the Symfony project.

New in Symfony 5.1: Form improvements

$
0
0

Added html5 option to ColorType

Thomas Calvet

Contributed by
Thomas Calvet
in #36302.

We added a new html5 option to ColorType form field. When this option is set to true, the form type checks that its value matches the HTML5 color format, which is /^#[0-9a-f]{6}$/i.

Added rounding_mode option to PercentType

Vincent Langlet

Contributed by
Vincent Langlet
in #35729.

The new rounding_mode option of the PercentType form field is useful in combination with the scale option, which defines the number of decimals allowed before applying the rounding.

The values of rounding_mode are any of the PHP \NumberFormatter constants (\NumberFormatter::ROUND_CEILING, \NumberFormatter::ROUND_HALFEVEN, etc.)

Allow HTML contents in form labels

Przemysław Bogusz

Contributed by
Przemysław Bogusz
in #31375.

HTML contents are escaped by default in form labels for security reasons. The new label_html boolean option allows a form field to include HTML contents in their labels, which is useful to display icons inside buttons, links and some formatting in checkbox/radiobutton labels, etc.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// src/Form/Type/TaskType.phpnamespaceApp\Form\Type;useSymfony\Component\Form\AbstractType;useSymfony\Component\Form\Extension\Core\Type\SubmitType;useSymfony\Component\Form\FormBuilderInterface;classTaskTypeextendsAbstractType{publicfunctionbuildForm(FormBuilderInterface$builder,array$options){$builder// ...->add('save',SubmitType::class,['label'=>'<i class="far fa-save"></i> Save','label_html'=>true,]);}}

Simpler reference_date in TimeType

Christian Flothmann

Contributed by
Christian Flothmann
in #35205.

In the TimeType form field, when you use different values for model_timezone and view_timezone, you must set the reference_date option. In Symfony 5.1, when no reference_date is set, the view_timezone defaults to the configured model_timezone.

Better default values for the inputmode option

Artem Henvald

Contributed by
Artem Henvald
in #34986.

The inputmode HTML attribute tells browsers which kind of data might be entered by the user while editing the element or its contents (e.g. a telephone number, an email address, a decimal number, etc.)

We already use this option in form fields like UrlType, but in Symfony 5.1 we decided to configure better default values for the inputmode in several fields:

  • inputmode = 'email' for EmailType;
  • inputmode = 'search' for SearchType;
  • inputmode = 'tel' for TelType.

Choice improvements

Jules Pietri

Contributed by
Jules Pietri
in #35733.

The new choice_filter option allows you to filter the default list of choices configured for a given form field. Use a PHP closure to decide if a choice should be kept or removed (and combine it with custom form type options for maximum flexibility):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// src/Form/Type/AddressType.phpnamespaceApp\Form\Type;useSymfony\Component\Form\AbstractType;useSymfony\Component\Form\Extension\Core\Type\CountryType;useSymfony\Component\Form\FormBuilderInterface;classAddressTypeextendsAbstractType{// ...publicfunctionbuildForm(FormBuilderInterface$builder,array$options){$builder// ...->add('country',CountryType::class,[// $allowedCountries is a custom form type option// closure returns TRUE to keep the choice and FALSE to remove it'choice_filter'=>$allowedCountries?function($countryCode)use($allowedCountries){returnin_array($countryCode,$allowedCountries,true);}:null,]);}

In addition, we updated the Symfony Forms internals to support caching choice lists based on options (see pull request #30994), providing between a 15% and 30% performance improvement.

Finally, we introduced an AbstractChoiceLoader to simplify the choice lazy-loading implementations and handle global optimizations (see pull request #34550).


Sponsor the Symfony project.

New in Symfony 5.1: HttpFoundation improvements

$
0
0

Added InputBag

Saif

Contributed by
Saif
in #34363.

The ParameterBag class defined by Symfony is like an object-oriented array which stores related values and provides methods such as get(), set(),has(), etc. Symfony defines specialized ParameterBag classes for some purposes (e.g. FileBag for uploaded files, ServerBag for HTTP headers, etc.)

In Symfony 5.1 we've introduced a new InputBag class (which extends fromParameterBag) to manage values provided by the user (via $_GET, $_POST,$_REQUEST, and $_COOKIE superglobals).

Encrypted session data

Ahmed Tailouloute

Contributed by
Ahmed Tailouloute
in #35804.

Encrypting data is one of the recommended ways to minimize the damage caused by security leaks. In Symfony 5.1 you can encrypt the contents of the session using a new MarshallingSessionHandler, which in turn uses the marshaller from the Cache component.

Use the following configuration to define the needed data to encrypt the sessions:

1
2
3
4
5
Symfony\Component\Cache\Marshaller\SodiumMarshaller:decorates:'session.marshaller'arguments:-['%env(file:resolve:SODIUM_DECRYPTION_FILE)%']-'@.inner'

Support all HTTP Cache-Control directives

Saif

Contributed by
Saif
in #35748.

Symfony supports the most used HTTP Cache-control directives (etag,last_modified, max_age, public , etc.). However, we were missing some of them, so we decided to add support for all cache-control directives in Symfony 5.1:

  • etag
  • immutable
  • last_modified
  • max_age
  • must_revalidate
  • no_cache
  • no_store
  • no_transform
  • private
  • proxy_revalidate
  • public
  • s_maxage

Sponsor the Symfony project.
Viewing all 3133 articles
Browse latest View live