CuyZ / Valinor

PHP library that helps to map any input into a strongly-typed value object structure.

Home Page:https://valinor.cuyz.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to serialize object collection, ArrayObject used

matak opened this issue · comments

I have this main Entity:

<?php

declare(strict_types=1);

namespace App\ApiModule\Entity\V1\ExpeditionPacking;

use Spatie\TypeScriptTransformer\Attributes\TypeScript;

#[TypeScript]
class CompletionPackageEntity
{

	public function __construct(
		/**
		 *
		 * @var string[]
		 */
		public array                                 $weightOfItems,
		/**
		 * @var ArrayOfCompletionPackageDokladEntity|null
		 */
		public ?ArrayOfCompletionPackageDokladEntity $data,
		public array                                 $EANtoProduktVarianta,
		public bool                                  $iAmNotOwner
	)
	{
		
	}

now code for ArrayOfCompletionPackageDokladEntity

<?php

declare(strict_types=1);

namespace App\ApiModule\Entity\V1\ExpeditionPacking;

use Romanmatena\PhpTools\Collections\ArrayCollection;
use Spatie\TypeScriptTransformer\Attributes\TypeScript;

#[TypeScript]
class ArrayOfCompletionPackageDokladEntity extends ArrayCollection
{

now ArrayCollection

<?php

namespace Romanmatena\PhpTools\Collections;

abstract class ArrayCollection extends \ArrayObject implements ICollection, \Traversable, \JsonSerializable
{
	/**
	 * @return array|object
	 */
	public function jsonSerialize(): array|object
	{
		return $this->toArray();
	}

if i use json_encode then data includes the objects in ArrayCollection but if i use normalizer, data is empty

$normalizer = (new \CuyZ\Valinor\MapperBuilder())
				->normalizer(\CuyZ\Valinor\Normalizer\Format::json());

			$content = $normalizer->normalize($completionPackageEntity);

do i missing something?

EDIT:

seems that problem is this row

$values = (fn () => get_object_vars($this))->call($value);

get_object_vars used for ArrayObject will not return array, is there any best practise how to solve it?

it means i need to not get inside of this condition

if (is_object($value) && ! $value instanceof Closure && ! $value instanceof Generator) {

but ArrayObject is not Closure or Generator and it is not possible for me to extend any of these

Thanks for the report! Should be fixed with #498. 😊