Skip to content

Commit 2fb12ed

Browse files
committed
Chore: Added docs for the new attribute.
1 parent d52e764 commit 2fb12ed

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
```

docs/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff 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

0 commit comments

Comments
 (0)