<?php
/**
 * BookiFlex Core
 *
 * @package    BookiFlex
 * @subpackage Core
 * @author     BookiFlex
 * @copyright  Copyright (c) 2025 BookiFlex
 * @license    GPL-2.0-or-later
 *
 * @link       https://bookiflex.com
 */

declare(strict_types=1);
namespace BookiFlex\Core\Util;

defined( 'ABSPATH' ) || exit;

/**
 * Iterable utilities for PHP 8.1 compatibility.
 *
 * In PHP 8.2 iterator_to_array() and iterator_count() accept iterable,
 * but in PHP 8.1 they only accept Traversable.
 */
class Iter
{
    /**
     * @template T
     * @param iterable<T> $items
     * @param bool $preserveKeys
     * @return array<T>
     */
    public static function toArray(iterable $items, bool $preserveKeys = true): array
    {
        if (is_array($items)) {
            return $items;
        }

        return iterator_to_array($items, $preserveKeys);
    }

    /**
     * @param iterable<mixed> $items
     */
    public static function count(iterable $items): int
    {
        if (is_array($items)) {
            return count($items);
        }

        if ($items instanceof \Countable) {
            return count($items);
        }

        return iterator_count($items);
    }
}