<?php

declare(strict_types=1);

namespace apexl\Io\services;

final class RecursionFinderService
{
    private array $data;

    public function find(array $data): array
    {
        $this->data = [];
        $this->findRecursion($data);

        return $this->data;
    }

    private function findRecursion(array $data, string $parent = ''): void
    {
        foreach ($data as &$item) {
            if (is_array($item)) {
                $this->findRecursion($item, $parent);
                continue;
            }

            if (is_object($item)) {
                $id = spl_object_id($item);
                $str = sprintf(
                    '[%s] %s%s%s',
                    $id,
                    get_class($item),
                    isset($item->id) ? " ($item->id)" : '',
                    $parent ? "| $parent" : '',
                );
                if (isset($item->components)) {
                    $this->findRecursion($item->components->toArray(), $str);
                }
                if (isset($item->props)) {
                    $this->findRecursion($item->props->toArray(), $str);

                }
                $this->data[$id] = $this->data[$id] ?? [];
                $this->data[$id][] = $str;
            }
        }
    }

}