File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed
Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+
2+ [ back to overview] ( ../README.md )
3+
4+ ---
5+
6+ ** Table of contents**
7+ - [ PhpSerializationFilter] ( #phpserializationfilter )
8+ - [Example](#example)
9+
10+ ---
11+
12+ # PhpSerializationFilter
13+
14+ Abstract class that can be implemented to modifiy the serialization output on a given property or field.
15+ To facilitate completely omitting fields, ` null ` returned from the ` Serialize ` method has special consideration in the
16+ serializer.
17+
18+ ## Example
19+
20+ ** Implementation:**
21+ ``` cs
22+ [AttributeUsage (AttributeTargets .Property | AttributeTargets .Field )]
23+ public class PhpIgnoreNull : PhpSerializationFilter {
24+ public override string ? Serialize (object key , object value , PhpSerializiationOptions options ) {
25+ if (value != null ) {
26+ return PhpSerialization .Serialize (key , options ) + PhpSerialization .Serialize (value , options );
27+ }
28+ return null ;
29+ }
30+ }
31+ ```
32+
33+ ** Usage:**
34+ ``` cs
35+ public struct PersonA {
36+ [PhpIgnoreNull ]
37+ public string ? Title { get ; set ; }
38+ public required string FirstName { get ; set ; }
39+ public required string LastName { get ; set ; }
40+ }
41+
42+ var serialized = PhpSerialization .Serialize (new PersonA { FirstName = " John" , LastName = " Johnson" });
43+ // serialized = "a:2:{s:9:"FirstName";s:4:"John";s:8:"LastName";s:7:"Johnson"}"
44+
45+ // in contrast without the custom filter:
46+ public struct PersonB {
47+ public string ? Title { get ; set ; }
48+ public required string FirstName { get ; set ; }
49+ public required string LastName { get ; set ; }
50+ }
51+
52+ var serialized = PhpSerialization .Serialize (new PersonB { FirstName = " John" , LastName = " Johnson" });
53+ // serialized = "a:3:{s:5:"Title";N;s:9:"FirstName";s:4:"John";s:8:"LastName";s:7:"Johnson"}"
54+ ```
Original file line number Diff line number Diff line change @@ -14,6 +14,7 @@ You can make some decisions about de/serialization directly on your class and st
1414* [ PhpClass] ( ./Attributes/PhpClass.md )
1515* [ PhpIgnore] ( ./Attributes/PhpIgnore.md )
1616* [ PhpProperty] ( ./Attributes/PhpProperty.md )
17+ * [ PhpSerializationFilter] ( ./Attributes/PhpSerializationFilter.md )
1718
1819### Options
1920
You can’t perform that action at this time.
0 commit comments