Passed
Push — 6.0 ( 70657e...b737f6 )
by Olivier
11:54
created

ErrorCollectionIterator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 5
rs 10
1
<?php
2
3
/*
4
 * This file is part of the ICanBoogie package.
5
 *
6
 * (c) Olivier Laviale <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ICanBoogie;
13
14
use IteratorAggregate;
15
use Traversable;
16
17
/**
18
 * Iterates over an error collection and return rendered errors.
19
 *
20
 * @implements IteratorAggregate<string, string>
21
 */
22
class ErrorCollectionIterator implements IteratorAggregate
23
{
24
    /**
25
     * @var ErrorRenderer|callable
26
     * @phpstan-var ErrorRenderer|(callable(Error,string $attribute,ErrorCollection):string)
27
     */
28
    private $render_error;
29
30
    /**
31
     * @phpstan-param ErrorRenderer|(callable(Error,string $attribute,ErrorCollection):string)|null $render_error
32
     */
33
    public function __construct(
34
        private readonly ErrorCollection $collection,
35
        ErrorRenderer|callable $render_error = null
36
    ) {
37
        $this->render_error = $render_error ?? fn(Error $error) => (string) $error;
38
    }
39
40
    /**
41
     * @return Traversable<string, string>
42
     */
43
    public function getIterator(): Traversable
44
    {
45
        foreach ($this->collection as $attribute => $error) {
46
            yield $attribute => $this->render_error($error, $attribute);
47
        }
48
    }
49
50
    /**
51
     * Renders an error into a string.
52
     */
53
    private function render_error(Error $error, string $attribute): string
54
    {
55
        return ($this->render_error)($error, $attribute, $this->collection);
56
    }
57
}
58