<?php

declare(strict_types=1);

namespace OCA\Talk\Vendor\CuyZ\Valinor\Normalizer;

use OCA\Talk\Vendor\CuyZ\Valinor\Normalizer\Transformer\EmptyObject;
use OCA\Talk\Vendor\CuyZ\Valinor\Normalizer\Transformer\Transformer;

/**
 * @api
 *
 * @implements Normalizer<array<mixed>|scalar|null>
 */
final class ArrayNormalizer implements Normalizer
{
    public function __construct(
        private Transformer $transformer,
    ) {}

    public function normalize(mixed $value): mixed
    {
        /** @var array<mixed>|scalar|null */
        return $this->format(
            $this->transformer->transform($value),
        );
    }

    private function format(mixed $value): mixed
    {
        if (is_iterable($value)) {
            if (! is_array($value)) {
                $value = iterator_to_array($value);
            }

            $value = array_map($this->format(...), $value);
        } elseif ($value instanceof EmptyObject) {
            return [];
        }

        return $value;
    }
}
