Project

General

Profile

Bug #95899 » SerializableEntityTrait.php

Trait - Marvin Buchmann, 2022-12-21 08:45

 
<?php
declare(strict_types=1);

namespace CYBOB\KroneDownloads\Serialization;

use TYPO3\CMS\Extbase\Persistence\ObjectStorage;

/**
* @package \CYBOB\KroneDownloads\Serialization
*/
trait SerializableEntityTrait
{
/**
* Unsets all properties of type ObjectStorage on serialization since they can not be serialized.
*
* @return array
*/
public function __serialize(): array
{
$data = get_object_vars($this);

foreach ($data as $key => $value) {
if ($value instanceof ObjectStorage) {
unset($data[$key]);
}
}

return $data;
}

/**
* Sets the object's properties and calls a method "initializeObject" which should initialize all object storages.
*
* @param $data
*
* @return void
*/
public function __unserialize($data): void
{
foreach ($data as $key => $value) {
$this->{$key} = $value;
}

if (method_exists($this, 'initializeObject')) {
$this->initializeObject();
}
}

/**
* Initializes all ObjectStorage properties by default.
*
* @return void
*/
public function initializeObject(): void
{
$data = get_object_vars($this);

foreach ($data as $key => $value) {
if ($value instanceof ObjectStorage) {
$this->{$key} = new ObjectStorage();
}
}
}
}
(4-4/4)