Passed
Pull Request — master (#3)
by Igor
04:05 queued 41s
created

OffsetResult::getSourceResult()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 0
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
        $this->generator->current();
37
    }
38
39
    /**
40
     * @throws \UnexpectedValueException
41
     *
42
     * @return mixed|null
43
     */
44
    public function fetch()
45
    {
46
        if ($this->generator->valid()) {
47
            $value = $this->generator->current();
48
            $this->generator->next();
49
50
            return $value;
51
        }
52
    }
53
54
    /**
55
     * @throws \UnexpectedValueException
56
     *
57
     * @return array
58
     */
59
    public function fetchAll()
60
    {
61
        $result = [];
62
        while (($data = $this->fetch()) || $data !== null) {
63
            $result[] = $data;
64
        }
65
66
        return $result;
67
    }
68
69
    /**
70
     * @return int
71
     */
72
    public function getTotalCount()
73
    {
74
        return $this->totalCount;
75
    }
76
77
    /**
78
     * @param \Generator $generator
79
     *
80
     * @throws \UnexpectedValueException
81
     *
82
     * @return \Generator
83
     */
84
    protected function execute(\Generator $generator)
85
    {
86
        foreach ($generator as $sourceResult) {
87
            if (!is_object($sourceResult) || !($sourceResult instanceof SourceResultInterface)) {
88
                throw new \UnexpectedValueException(sprintf(
89
                    'Result of generator is not an instance of %s',
90
                    SourceResultInterface::class
91
                ));
92
            }
93
94
            $sourceCount = $sourceResult->getTotalCount();
95
            if ($sourceCount > $this->totalCount) {
96
                $this->totalCount = $sourceCount;
97
            }
98
99
            foreach ($sourceResult->generator() as $result) {
100
                yield $result;
101
            }
102
        }
103
    }
104
}
105