<?php

declare(strict_types=1);

namespace Gls\GlsPoland\Soap\Engine\Metadata\Collection;

use Gls\GlsPoland\Soap\Engine\Exception\MetadataException;
use Gls\GlsPoland\Soap\Engine\Metadata\Model\Method;

/**
 * @implements \IteratorAggregate<int, Method>
 */
final class MethodCollection implements \Countable, \IteratorAggregate
{
    /**
     * @var list<Method>
     */
    private $methods;

    /**
     * @no-named-arguments
     */
    public function __construct(Method ...$methods)
    {
        $this->methods = $methods;
    }

    /**
     * @return \Iterator<int, Method>
     */
    public function getIterator(): \Iterator
    {
        return new \ArrayIterator($this->methods);
    }

    public function count(): int
    {
        return count($this->methods);
    }

    public function map(callable $callback): array
    {
        return array_map($callback, $this->methods);
    }

    /**
     * @throws MetadataException
     */
    public function getByName(string $name): Method
    {
        foreach ($this->methods as $method) {
            if ($name === $method->getName()) {
                return $method;
            }
        }

        throw MetadataException::methodNotFound($name);
    }
}
