Yieldable::yieldKeyVal()   A
last analyzed

Complexity

Conditions 6
Paths 12

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 8
c 2
b 0
f 0
dl 0
loc 16
rs 9.2222
cc 6
nc 12
nop 2
1
<?php
2
3
namespace Dynamic\Salsify\Traits;
4
5
/**
6
 * Trait Yieldable
7
 * @package Dynamic\Salsify\Traits
8
 */
9
trait Yieldable
10
{
11
12
    /**
13
     * @var string
14
     */
15
    public static $STOP_GENERATOR = 'stop';
16
17
    /**
18
     * @param array|iterable $list
19
     * @param callable|null $callback
20
     * @return \Generator
21
     */
22
    public function yieldSingle($list, $callback = null)
23
    {
24
        if (!is_array($list) && !$list instanceof \Traversable) {
25
            $list = [$list];
26
        }
27
28
        foreach ($list as $item) {
29
            $injected = (yield $item);
30
31
            if ($injected === static::$STOP_GENERATOR) {
32
                break;
33
            }
34
        }
35
36
        if (is_callable($callback)) {
37
            $this->callback();
0 ignored issues
show
Bug introduced by
It seems like callback() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

37
            $this->/** @scrutinizer ignore-call */ 
38
                   callback();
Loading history...
38
        }
39
    }
40
41
    /**
42
     * @param array|iterable $list
43
     * @param callable|null $callback
44
     * @return \Generator
45
     */
46
    public function yieldKeyVal($list, $callback = null)
47
    {
48
        if (!is_array($list) && !$list instanceof \Traversable) {
49
            $list = [$list];
50
        }
51
52
        foreach ($list as $key => $val) {
53
            $injected = (yield $key => $val);
54
55
            if ($injected === static::$STOP_GENERATOR) {
56
                break;
57
            }
58
        }
59
60
        if (is_callable($callback)) {
61
            $this->callback();
62
        }
63
    }
64
}
65