OffsetResult::execute()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 11
nc 6
nop 1
1
<?php
2
3
/*
4
 * This file is part of the SomeWork/OffsetPage package.
5
 *
6
 * (c) Pinchuk Igor <[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 SomeWork\OffsetPage;
13
14
class OffsetResult
15
{
16
    /**
17
     * @var int
18
     */
19
    protected $totalCount = 0;
20
21
    /**
22
     * @var \Generator
23
     */
24
    protected $generator;
25
26
    /**
27
     * OffsetResult constructor.
28
     *
29
     * @param \Generator $sourceResultGenerator
30
     *
31
     * @throws \UnexpectedValueException
32
     */
33
    public function __construct(\Generator $sourceResultGenerator)
34
    {
35
        $this->generator = $this->execute($sourceResultGenerator);
36
        if ($this->generator->valid()) {
37
            $this->generator->current();
38
        }
39
    }
40
41
    /**
42
     * @throws \UnexpectedValueException
43
     *
44
     * @return mixed|null
45
     */
46
    public function fetch()
47
    {
48
        if ($this->generator->valid()) {
49
            $value = $this->generator->current();
50
            $this->generator->next();
51
52
            return $value;
53
        }
54
    }
55
56
    /**
57
     * @throws \UnexpectedValueException
58
     *
59
     * @return array
60
     */
61
    public function fetchAll()
62
    {
63
        $result = [];
64
        while (($data = $this->fetch()) || $data !== null) {
65
            $result[] = $data;
66
        }
67
68
        return $result;
69
    }
70
71
    /**
72
     * @return int
73
     */
74
    public function getTotalCount()
75
    {
76
        return $this->totalCount;
77
    }
78
79
    /**
80
     * @param \Generator $generator
81
     *
82
     * @throws \UnexpectedValueException
83
     *
84
     * @return \Generator
85
     */
86
    protected function execute(\Generator $generator)
87
    {
88
        foreach ($generator as $sourceResult) {
89
            if (!is_object($sourceResult) || !($sourceResult instanceof SourceResultInterface)) {
90
                throw new \UnexpectedValueException(sprintf(
91
                    'Result of generator is not an instance of %s',
92
                    SourceResultInterface::class
93
                ));
94
            }
95
96
            $sourceCount = $sourceResult->getTotalCount();
97
            if ($sourceCount > $this->totalCount) {
98
                $this->totalCount = $sourceCount;
99
            }
100
101
            foreach ($sourceResult->generator() as $result) {
102
                yield $result;
103
            }
104
        }
105
    }
106
}
107