|
1 | 1 | Lendable JSON Serializer |
2 | 2 | ============= |
3 | | -Provides an object oriented interface for handling json in php. |
| 3 | +Provides an opinionated object oriented interface for handling JSON serialization and deserialization in PHP. |
4 | 4 |
|
5 | | -Instead of failing silently, this lib will throw exceptions on json errors. |
| 5 | +## Features |
| 6 | +* Throws exceptions on serialization and deserialization failure. |
| 7 | +* Sane default serialization flags. |
6 | 8 |
|
7 | 9 | ## Installation |
8 | | -```bash |
9 | | -composer require lendable/json-serializer |
10 | | -``` |
| 10 | + ```bash |
| 11 | + composer require lendable/json-serializer |
| 12 | + ``` |
| 13 | + |
| 14 | +## Why? Opinionated? |
| 15 | +This library aids to simplify our most common usage patterns of JSON at Lendable by providing a strict and limited API, and not a generic solution. |
| 16 | + |
| 17 | +### Type safety |
| 18 | +We follow the pattern of converting object graph(s) to data array(s) and then to JSON, this library fits into the `data array(s) <=> json` part of that flow. Due to this, it is restrictive in what can be serialized and deserialized as for our use case, these are error conditions. Data is deserialized always as a numeric (array root element) or an associative array (object root element). Therefore, this library may _not_ fit your use case. |
| 19 | + |
| 20 | +### Error handling |
| 21 | +The default `json_encode()` and `json_decode()` global functions from `ext-json` are still used, but delegated to in a safe manner. The potential error reporting from these functions can be: |
| 22 | + |
| 23 | +* A `false` return value - except `json_decode('false')` also returns false, and isn't an error. |
| 24 | +* Retrieved as code or message via `json_last_error()` or `json_last_error_msg()` - requires being checked every time. |
| 25 | +* An exception via the `JSON_THROW_ON_ERROR` option in PHP 7.3 - requires opt-in to the functionality. |
| 26 | + |
| 27 | +This library will always throw exceptions on serialization and deserialization failures, simplifying calling logic. |
| 28 | + |
| 29 | +## API |
| 30 | + |
| 31 | +### Serialization `Serializer::serialize(array $data): string` |
| 32 | +Serializes a data array into a JSON string. |
| 33 | + |
| 34 | +Throws `SerializationFailed` on failure to serialize. |
| 35 | + |
| 36 | +### Deserialization `Serializer::deserialize(string $json): array` |
| 37 | +Deserializes a JSON string into an `array`. |
| 38 | + |
| 39 | +Throws `DeserializationFailed` on failure to deserialize. |
| 40 | +Throws `InvalidDeserializedData` if the data type of the resulting deserialized data is not an `array`. |
| 41 | + |
| 42 | + |
0 commit comments