Skip to content
Snippets Groups Projects
Verified Commit f36d332a authored by William Desportes's avatar William Desportes :sailboat:
Browse files

New upstream version 3.0.1

parent 77dcaf88
No related branches found
No related tags found
No related merge requests found
name: JSON Serializer CI
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
jobs:
testsuite:
runs-on: ubuntu-latest
strategy:
matrix:
php-version: ['7.0', '7.1', '7.2', '7.3', '7.4', '8.0']
name: PHP ${{ matrix.php-version }}
steps:
- uses: actions/checkout@v2
- name: Validate composer.json and composer.lock
run: composer validate
- name: Cache Composer packages
id: composer-cache
uses: actions/cache@v2
with:
path: vendor
key: ${{ runner.os }}-php-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-
- name: Install suggested dependencies
run: composer require jeremeamia/superclosure
- name: Install dependencies
if: steps.composer-cache.outputs.cache-hit != 'true'
run: composer install --prefer-dist --no-progress --no-suggest
- name: Run test suite
run: vendor/bin/phpunit
.idea
.phpunit.result.cache
vendor
composer.lock
# Change Log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
## [3.0.0] - 2020-07-20
### Fixed
- Fixed DateTime & DateTimeImmutable serialization in PHP 7.4+. Thanks @przemyslaw-bogusz
- Testing for PHP 7.3 and 7.4
### Changed
- Minimum PHP version supported is now 7.0
- Updated PHPUnit version to 6.x
### Removed
- Deprecated namespace `Zumba\Util`
## [2.2.0] - 2018-02-07
### Added
- Allowing to change the undeclared property unserialization mode
## [2.1.0] - 2016-05-22
### Changed
- Throwing exception if cannot encode JSON when serializing
- Throwing exception if cannot decode JSON when unserializing
### Deprecated
- Changed namespace from `Zumba\Util` to `Zumba\JsonSerializer`
## [2.0.1] - 2016-03-17
### Fixed
- Fixing float serialization on i18n locales
## [2.0.0] - 2016-02-26
### Added
- Support PHP closures serialization
### Removed
- Dropped support to PHP 5.3
### Changed
- Documentation improvements
- Support to PHP built-in support to float numbers without decimal points
- Using PSR-2 and PSR-4
## [1.0.1] - 2014-07-05
### Added
- Support to DateTime serialization
- Support to unescaped unicode
## [1.0.1] - 2014-04-12
### Fixed
- Fixed serialization of float numbers without decimal points
## [1.0.0] - 2014-01-06
### Added
- Encode/Decode of scalar, null, array
- Encode/Decode of objects
- Support nested serialization
- Support not declared properties on the original class definition (ie, properties in stdClass)
- Support object recursion
LICENSE 0 → 100644
The MIT License (MIT)
Copyright (c) 2016 Zumba(r)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
README.md 0 → 100644
# Json Serializer for PHP
<p align="center">
<a href="LICENSE.txt" target="_blank">
<img alt="Software License" src="https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square">
</a>
<img alt="Build Status" src="https://github.com/zumba/json-serializer/actions/workflows/php.yml/badge.svg?branch=master">
<a href="https://packagist.org/packages/zumba/json-serializer" target="_blank">
<img alt="Total Downloads" src="https://img.shields.io/packagist/dt/zumba/json-serializer.svg?style=flat-square">
</a>
<a href="https://packagist.org/packages/zumba/json-serializer" target="_blank">
<img alt="Latest Stable Version" src="https://img.shields.io/packagist/v/zumba/json-serializer.svg?style=flat-square&label=stable">
</a>
</p>
This is a library to serialize PHP variables in JSON format. It is similar of the `serialize()` function in PHP,
but the output is a string JSON encoded. You can also unserialize the JSON generated by this tool and have you
PHP content back.
Supported features:
- Encode/Decode of scalar, null, array
- Encode/Decode of objects
- Encode/Decode of binary data
- Support nested serialization
- Support not declared properties on the original class definition (ie, properties in `stdClass`)
- Support object recursion
- Closures (via 3rd party library. See details below)
Unsupported serialization content:
- Resource (ie, `fopen()` response)
- NAN, INF constants
Limitations:
- Binary data containing null bytes (\u0000) as array keys cannot be properly decoded because of a json extension bug:
- https://github.com/remicollet/pecl-json-c/issues/7
- https://github.com/json-c/json-c/issues/108
This project should not be confused with `JsonSerializable` interface added on PHP 5.4. This interface is used on
`json_encode` to encode the objects. There is no unserialization with this interface, differently from this project.
*Json Serializer requires PHP >= 7.0 and tested until PHP 7.4*
## Example
```php
class MyCustomClass {
public $isItAwesome = true;
protected $nice = 'very!';
}
$instance = new MyCustomClass();
$serializer = new Zumba\JsonSerializer\JsonSerializer();
$json = $serializer->serialize($instance);
// $json will contain the content {"@type":"MyCustomClass","isItAwesome":true,"nice":"very!"}
$restoredInstance = $serializer->unserialize($json);
// $restoredInstance will be an instance of MyCustomClass
```
## How to Install
If you are using composer, install the package [`zumba/json-serializer`](https://packagist.org/packages/zumba/json-serializer).
```
$ composer require zumba/json-serializer
```
Or add the `zumba/json-serializer` directly in your `composer.json` file.
If you are not using composer, you can just copy the files from `src` folder in your project.
## Serializing Binary Strings
Binary strings introduce two special identifiers in the final json: `@utf8encoded` and `@scalar`.
`@utf8encoded` is an array of keys from the original data which have their value (or the keys themselves)
encoded from 8bit to UTF-8. This is how the serializer knows what to encode back from UTF-8 to 8bit when deserializing.
Example:
```php
$data = ['key' => '<binaryvalue>', 'anotherkey' => 'nonbinaryvalue'];
$serializer = new Zumba\JsonSerializer\JsonSerializer();
$json = $serializer->serialize($data);
// $json will contain the content {"key":"<utf8encodedbinaryvalue>","anotherkey":"nonbinaryvalue","@utf8encoded":{"key":1}}
```
`@scalar` is used only when the value to be encoded is not an array or an object but a binary string. Example:
```php
$data = '<binaryvalue>';
$serializer = new Zumba\JsonSerializer\JsonSerializer();
$json = $serializer->serialize($data);
// $json will contain the content {"@scalar":"<utf8encodedbinaryvalue>","@utf8encoded":1}
```
## Serializing Closures
For serializing PHP closures you have to pass an object implementing `SuperClosure\SerializerInterface`.
This interface is provided by the project [SuperClosure](https://github.com/jeremeamia/super_closure). This
project also provides a closure serializer that implements this interface.
Closure serialization has some limitations. Please check the SuperClosure project to check if it fits your
needs.
To use the SuperClosure with JsonSerializer, just pass the SuperClosure object as the first parameter
on JsonSerializer constructor. Example:
```php
$toBeSerialized = array(
'data' => array(1, 2, 3),
'worker' => function ($data) {
$double = array();
foreach ($data as $i => $number) {
$double[$i] = $number * 2;
}
return $double;
}
);
$superClosure = new SuperClosure\Serializer();
$jsonSerializer = new Zumba\JsonSerializer\JsonSerializer($superClosure);
$serialized = $jsonSerializer->serialize($toBeSerialized);
```
PS: JsonSerializer does not have a hard dependency of SuperClosure. If you want to use both projects
make sure you add both on your composer requirements.
## Custom Serializers
Some classes may not be suited to be serialized and unserialized using the default reflection methods.
Custom serializers provide the ability to define ```serialize``` and ```unserialize``` methods for specific classes.
```php
class MyType {
public $field1;
public $field2;
}
class MyTypeSerializer {
public function serialize(MyType $obj) {
return array('fields' => $obj->field1 . ' ' . $obj->field2);
}
public function unserialize($values) {
list($field1, $field2) = explode(' ', $values['fields']);
$obj = new MyType();
$obj->field1 = $field1;
$obj->field2 = $field2;
return $obj;
}
}
// map of "class name" => Custom serializer
$customObjectSerializers['MyType'] = new MyTypeSerializer();
$jsonSerializer = new Zumba\JsonSerializer\JsonSerializer(null, $customObjectSerializers);
$toBeSerialized = new MyType();
$toBeSerialized->field1 = 'x';
$toBeSerialized->field2 = 'y';
$json = $jsonSerializer->serialize($toBeSerialized);
// $json == {"@type":"Zumba\\\\JsonSerializer\\\\Test\\\\SupportClasses\\\\MyType","fields":"x y"}
$myType = $jsonSerializer->unserialize($json);
// $myType == $toBeSerialized
```
{
"name": "zumba/json-serializer",
"type": "library",
"description": "Serialize PHP variables, including objects, in JSON format. Support to unserialize it too.",
"keywords": ["json", "serialize", "serializer"],
"homepage": "http://tech.zumba.com",
"license": "MIT",
"scripts": {
"test": "phpunit --colors=always"
},
"authors": [
{
"name": "Zumba Fitness, LLC",
"email": "engineering@zumba.com"
},
{
"name": "Juan Basso",
"email": "juan.basso@zumba.com"
}
],
"require": {
"php": ">=7.0.0",
"ext-mbstring": "*"
},
"suggest": {
"jeremeamia/superclosure": "Allow to serialize PHP closures"
},
"require-dev": {
"phpunit/phpunit": ">=6.0 <10.0"
},
"autoload": {
"psr-4": {
"Zumba\\": "src/",
"Zumba\\JsonSerializer\\Test\\": "tests/"
}
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
colors="true">
<testsuites>
<testsuite name="JsonSerializerTests">
<directory>./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist addUncoveredFilesFromWhitelist="true">
<directory>./src</directory>
</whitelist>
</filter>
</phpunit>
<?php
namespace Zumba\JsonSerializer\Exception;
use RuntimeException;
class JsonSerializerException extends RuntimeException
{
}
<?php
namespace Zumba\JsonSerializer;
use InvalidArgumentException;
use ReflectionClass;
use ReflectionException;
use SplObjectStorage;
use Zumba\JsonSerializer\Exception\JsonSerializerException;
use SuperClosure\SerializerInterface as ClosureSerializerInterface;
class JsonSerializer
{
const CLASS_IDENTIFIER_KEY = '@type';
const CLOSURE_IDENTIFIER_KEY = '@closure';
const UTF8ENCODED_IDENTIFIER_KEY = '@utf8encoded';
const SCALAR_IDENTIFIER_KEY = '@scalar';
const FLOAT_ADAPTER = 'JsonSerializerFloatAdapter';
const KEY_UTF8ENCODED = 1;
const VALUE_UTF8ENCODED = 2;
const UNDECLARED_PROPERTY_MODE_SET = 1;
const UNDECLARED_PROPERTY_MODE_IGNORE = 2;
const UNDECLARED_PROPERTY_MODE_EXCEPTION = 3;
/**
* Storage for object
*
* Used for recursion
*
* @var SplObjectStorage
*/
protected $objectStorage;
/**
* Object mapping for recursion
*
* @var array
*/
protected $objectMapping = [];
/**
* Object mapping index
*
* @var integer
*/
protected $objectMappingIndex = 0;
/**
* Closure serializer instance
*
* @var ClosureSerializerInterface
*/
protected $closureSerializer;
/**
* Map of custom object serializers
*
* @var array
*/
protected $customObjectSerializerMap;
/**
* Undefined Attribute Mode
*
* @var integer
*/
protected $undefinedAttributeMode = self::UNDECLARED_PROPERTY_MODE_SET;
/**
* Constructor.
*
* @param ClosureSerializerInterface $closureSerializer
* @param array $customObjectSerializerMap
*/
public function __construct(
ClosureSerializerInterface $closureSerializer = null,
$customObjectSerializerMap = []
) {
$this->closureSerializer = $closureSerializer;
$this->customObjectSerializerMap = (array)$customObjectSerializerMap;
}
/**
* Serialize the value in JSON
*
* @param mixed $value
* @return string JSON encoded
* @throws JsonSerializerException
*/
public function serialize($value)
{
$this->reset();
$serializedData = $this->serializeData($value);
$encoded = json_encode($serializedData, $this->calculateEncodeOptions());
if ($encoded === false || json_last_error() != JSON_ERROR_NONE) {
if (json_last_error() != JSON_ERROR_UTF8) {
throw new JsonSerializerException('Invalid data to encode to JSON. Error: ' . json_last_error());
}
$serializedData = $this->encodeNonUtf8ToUtf8($serializedData);
$encoded = json_encode($serializedData, $this->calculateEncodeOptions());
if ($encoded === false || json_last_error() != JSON_ERROR_NONE) {
throw new JsonSerializerException('Invalid data to encode to JSON. Error: ' . json_last_error());
}
}
return $this->processEncodedValue($encoded);
}
/**
* Calculate encoding options
*
* @return integer
*/
protected function calculateEncodeOptions()
{
return JSON_UNESCAPED_UNICODE | JSON_PRESERVE_ZERO_FRACTION;
}
/**
*
* @param mixed $serializedData
*
* @return array
*/
protected function encodeNonUtf8ToUtf8($serializedData)
{
if (is_string($serializedData)) {
if (!mb_check_encoding($serializedData, 'UTF-8')) {
$serializedData = [
static::SCALAR_IDENTIFIER_KEY => mb_convert_encoding($serializedData, 'UTF-8', '8bit'),
static::UTF8ENCODED_IDENTIFIER_KEY => static::VALUE_UTF8ENCODED,
];
}
return $serializedData;
}
$encodedKeys = [];
$encodedData = [];
foreach ($serializedData as $key => $value) {
if (is_array($value)) {
$value = $this->encodeNonUtf8ToUtf8($value);
}
if (!mb_check_encoding($key, 'UTF-8')) {
$key = mb_convert_encoding($key, 'UTF-8', '8bit');
$encodedKeys[$key] = isset($encodedKeys[$key]) ? $encodedKeys[$key] : 0;
$encodedKeys[$key] |= static::KEY_UTF8ENCODED;
}
if (is_string($value)) {
if (!mb_check_encoding($value, 'UTF-8')) {
$value = mb_convert_encoding($value, 'UTF-8', '8bit');
$encodedKeys[$key] = isset($encodedKeys[$key]) ? $encodedKeys[$key] : 0;
$encodedKeys[$key] |= static::VALUE_UTF8ENCODED;
}
}
$encodedData[$key] = $value;
}
if ($encodedKeys) {
$encodedData[self::UTF8ENCODED_IDENTIFIER_KEY] = $encodedKeys;
}
return $encodedData;
}
/**
* Execute post-encoding actions
*
* @param string $encoded
* @return string
*/
protected function processEncodedValue($encoded)
{
return $encoded;
}
/**
* Unserialize the value from JSON
*
* @param string $value
* @return mixed
*/
public function unserialize($value)
{
$this->reset();
$data = json_decode($value, true);
if ($data === null && json_last_error() != JSON_ERROR_NONE) {
throw new JsonSerializerException('Invalid JSON to unserialize.');
}
if (mb_strpos($value, static::UTF8ENCODED_IDENTIFIER_KEY) !== false) {
$data = $this->decodeNonUtf8FromUtf8($data);
}
return $this->unserializeData($data);
}
/**
* Set unserialization mode for undeclared class properties
*
* @param integer $value One of the JsonSerializer::UNDECLARED_PROPERTY_MODE_*
* @return self
* @throws InvalidArgumentException When the value is not one of the UNDECLARED_PROPERTY_MODE_* options
*/
public function setUnserializeUndeclaredPropertyMode($value)
{
$availableOptions = [
static::UNDECLARED_PROPERTY_MODE_SET,
static::UNDECLARED_PROPERTY_MODE_IGNORE,
static::UNDECLARED_PROPERTY_MODE_EXCEPTION
];
if (!in_array($value, $availableOptions)) {
throw new InvalidArgumentException('Invalid value.');
}
$this->undefinedAttributeMode = $value;
return $this;
}
/**
* Parse the data to be json encoded
*
* @param mixed $value
* @return mixed
* @throws JsonSerializerException
*/
protected function serializeData($value)
{
if (is_scalar($value) || $value === null) {
return $value;
}
if (is_resource($value)) {
throw new JsonSerializerException('Resource is not supported in JsonSerializer');
}
if (is_array($value)) {
return array_map([$this, __FUNCTION__], $value);
}
if ($value instanceof \Closure) {
if (!$this->closureSerializer) {
throw new JsonSerializerException('Closure serializer not given. Unable to serialize closure.');
}
return [
static::CLOSURE_IDENTIFIER_KEY => true,
'value' => $this->closureSerializer->serialize($value)
];
}
return $this->serializeObject($value);
}
/**
* Extract the data from an object
*
* @param object $value
* @return array
*/
protected function serializeObject($value)
{
if ($this->objectStorage->contains($value)) {
return [static::CLASS_IDENTIFIER_KEY => '@' . $this->objectStorage[$value]];
}
$this->objectStorage->attach($value, $this->objectMappingIndex++);
$ref = new ReflectionClass($value);
$className = $ref->getName();
if (array_key_exists($className, $this->customObjectSerializerMap)) {
$data = [static::CLASS_IDENTIFIER_KEY => $className];
$data += $this->customObjectSerializerMap[$className]->serialize($value);
return $data;
}
$data = [static::CLASS_IDENTIFIER_KEY => $className];
if ($value instanceof \DateTimeInterface) {
return $data + (array) $value;
}
if ($value instanceof \SplDoublyLinkedList) {
return $data + ['value' => $value->serialize()];
}
$paramsToSerialize = $this->getObjectProperties($ref, $value);
$data += array_map([$this, 'serializeData'], $this->extractObjectData($value, $ref, $paramsToSerialize));
return $data;
}
/**
* Return the list of properties to be serialized
*
* @param ReflectionClass $ref
* @param object $value
* @return array
*/
protected function getObjectProperties($ref, $value)
{
if (method_exists($value, '__sleep')) {
return $value->__sleep();
}
$props = [];
foreach ($ref->getProperties() as $prop) {
$props[] = $prop->getName();
}
return array_unique(array_merge($props, array_keys(get_object_vars($value))));
}
/**
* Extract the object data
*
* @param object $value
* @param ReflectionClass $ref
* @param array $properties
* @return array
*/
protected function extractObjectData($value, $ref, $properties)
{
$data = [];
foreach ($properties as $property) {
try {
$propRef = $ref->getProperty($property);
$propRef->setAccessible(true);
$data[$property] = $propRef->getValue($value);
} catch (ReflectionException $e) {
$data[$property] = $value->$property;
}
}
return $data;
}
/**
* Parse the json decode to convert to objects again
*
* @param mixed $value
* @return mixed
*/
protected function unserializeData($value)
{
if (is_scalar($value) || $value === null) {
return $value;
}
if (isset($value[static::CLASS_IDENTIFIER_KEY])) {
return $this->unserializeObject($value);
}
if (!empty($value[static::CLOSURE_IDENTIFIER_KEY])) {
if (!$this->closureSerializer) {
throw new JsonSerializerException('Closure serializer not provided to unserialize closure');
}
return $this->closureSerializer->unserialize($value['value']);
}
return array_map([$this, __FUNCTION__], $value);
}
/**
*
* @param mixed $serializedData
*
* @return mixed
*/
protected function decodeNonUtf8FromUtf8($serializedData)
{
if (is_array($serializedData) && isset($serializedData[static::SCALAR_IDENTIFIER_KEY])) {
$serializedData = mb_convert_encoding($serializedData[static::SCALAR_IDENTIFIER_KEY], '8bit', 'UTF-8');
return $serializedData;
} elseif (is_scalar($serializedData) || $serializedData === null) {
return $serializedData;
}
$encodedKeys = [];
if (isset($serializedData[static::UTF8ENCODED_IDENTIFIER_KEY])) {
$encodedKeys = $serializedData[static::UTF8ENCODED_IDENTIFIER_KEY];
unset($serializedData[static::UTF8ENCODED_IDENTIFIER_KEY]);
}
$decodedData = [];
foreach ($serializedData as $key => $value) {
if (is_array($value)) {
$value = $this->decodeNonUtf8FromUtf8($value);
}
if (isset($encodedKeys[$key])) {
$originalKey = $key;
if ($encodedKeys[$key] & static::KEY_UTF8ENCODED) {
$key = mb_convert_encoding($key, '8bit', 'UTF-8');
}
if ($encodedKeys[$originalKey] & static::VALUE_UTF8ENCODED) {
$value = mb_convert_encoding($value, '8bit', 'UTF-8');
}
}
$decodedData[$key] = $value;
}
return $decodedData;
}
/**
* Convert the serialized array into an object
*
* @param array $value
* @return object
* @throws JsonSerializerException
*/
protected function unserializeObject($value)
{
$className = $value[static::CLASS_IDENTIFIER_KEY];
unset($value[static::CLASS_IDENTIFIER_KEY]);
if ($className[0] === '@') {
$index = substr($className, 1);
return $this->objectMapping[$index];
}
if (array_key_exists($className, $this->customObjectSerializerMap)) {
$obj = $this->customObjectSerializerMap[$className]->unserialize($value);
$this->objectMapping[$this->objectMappingIndex++] = $obj;
return $obj;
}
if (!class_exists($className)) {
throw new JsonSerializerException('Unable to find class ' . $className);
}
if ($className === 'DateTime') {
$obj = $this->restoreUsingUnserialize($className, $value);
$this->objectMapping[$this->objectMappingIndex++] = $obj;
return $obj;
}
if (!$this->isSplList($className)) {
$ref = new ReflectionClass($className);
$obj = $ref->newInstanceWithoutConstructor();
} else {
$obj = new $className();
}
if ($obj instanceof \SplDoublyLinkedList) {
$obj->unserialize($value['value']);
$this->objectMapping[$this->objectMappingIndex++] = $obj;
return $obj;
}
$this->objectMapping[$this->objectMappingIndex++] = $obj;
foreach ($value as $property => $propertyValue) {
try {
$propRef = $ref->getProperty($property);
$propRef->setAccessible(true);
$propRef->setValue($obj, $this->unserializeData($propertyValue));
} catch (ReflectionException $e) {
switch ($this->undefinedAttributeMode) {
case static::UNDECLARED_PROPERTY_MODE_SET:
$obj->$property = $this->unserializeData($propertyValue);
break;
case static::UNDECLARED_PROPERTY_MODE_IGNORE:
break;
case static::UNDECLARED_PROPERTY_MODE_EXCEPTION:
throw new JsonSerializerException('Undefined attribute detected during unserialization');
break;
}
}
}
if (method_exists($obj, '__wakeup')) {
$obj->__wakeup();
}
return $obj;
}
/**
*
* @return boolean
*/
protected function isSplList($className)
{
return in_array($className, ['SplQueue', 'SplDoublyLinkedList', 'SplStack']);
}
protected function restoreUsingUnserialize($className, $attributes)
{
$obj = (object)$attributes;
$serialized = preg_replace(
'|^O:\d+:"\w+":|',
'O:' . strlen($className) . ':"' . $className . '":',
serialize($obj)
);
return unserialize($serialized);
}
/**
* Reset variables
*
* @return void
*/
protected function reset()
{
$this->objectStorage = new SplObjectStorage();
$this->objectMapping = [];
$this->objectMappingIndex = 0;
}
}
This diff is collapsed.
<?php
namespace Zumba\JsonSerializer\Test\SupportClasses;
class AllVisibilities
{
public $pub = 'this is public';
protected $prot = 'protected';
private $priv = 'dont tell anyone';
}
<?php
namespace Zumba\JsonSerializer\Test\SupportClasses;
class EmptyClass
{
}
<?php
namespace Zumba\JsonSerializer\Test\SupportClasses;
class MagicClass
{
public $show = true;
public $hide = true;
public $woke = false;
public function __sleep()
{
return array('show');
}
public function __wakeup()
{
$this->woke = true;
}
}
<?php
namespace Zumba\JsonSerializer\Test\SupportClasses;
class MyType
{
public $field1;
public $field2;
}
<?php
namespace Zumba\JsonSerializer\Test\SupportClasses;
class MyTypeSerializer
{
public function serialize(MyType $obj)
{
return array('fields' => $obj->field1 . ' ' . $obj->field2);
}
public function unserialize($values)
{
list($field1, $field2) = explode(' ', $values['fields']);
$obj = new MyType();
$obj->field1 = $field1;
$obj->field2 = $field2;
return $obj;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment