1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Eclipxe\XlsxExporter\Providers; |
6
|
|
|
|
7
|
|
|
use Countable; |
8
|
|
|
use Eclipxe\XlsxExporter\ProviderInterface; |
9
|
|
|
use Eclipxe\XlsxExporter\Utils\ProviderGetValue; |
10
|
|
|
use Iterator; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* ProviderIterator is a facade to be able to use any Iterator as a Provider |
14
|
|
|
* |
15
|
|
|
* The iterator current method must return an array, an ArrayAccess or an object, |
16
|
|
|
* the code will check if the key is set in the element, if it is not set then |
17
|
|
|
* will return null |
18
|
|
|
* |
19
|
|
|
* As the Iterator does not know the length of the elements by itself then it is |
20
|
|
|
* desirable to provide the total count from the constructor. |
21
|
|
|
* If a negative number is provided then the function will traverse the hole iterator |
22
|
|
|
* to count the total elements. |
23
|
|
|
*/ |
24
|
|
|
class ProviderIterator implements ProviderInterface |
25
|
|
|
{ |
26
|
|
|
private Iterator $iterator; |
27
|
|
|
|
28
|
|
|
private int $count; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* ProviderIterator constructor. |
32
|
|
|
* @param Iterator $iterator |
33
|
|
|
* @param int $count The total count of records, -1 to obtain |
34
|
|
|
*/ |
35
|
5 |
|
public function __construct(Iterator $iterator, int $count = -1) |
36
|
|
|
{ |
37
|
5 |
|
$this->iterator = $iterator; |
38
|
5 |
|
if (! is_int($count) || $count < 0) { |
39
|
2 |
|
if ($this->iterator instanceof Countable) { |
40
|
1 |
|
$count = $this->iterator->count(); |
|
|
|
|
41
|
|
|
} else { |
42
|
1 |
|
$count = iterator_count($this->iterator); |
43
|
1 |
|
$this->iterator->rewind(); |
44
|
|
|
} |
45
|
|
|
} |
46
|
5 |
|
$this->count = $count; |
47
|
|
|
} |
48
|
|
|
|
49
|
5 |
|
public function get(string $key) |
50
|
|
|
{ |
51
|
5 |
|
return ProviderGetValue::get($this->iterator->current(), $key); |
52
|
|
|
} |
53
|
|
|
|
54
|
5 |
|
public function next(): void |
55
|
|
|
{ |
56
|
5 |
|
$this->iterator->next(); |
57
|
|
|
} |
58
|
|
|
|
59
|
5 |
|
public function valid(): bool |
60
|
|
|
{ |
61
|
5 |
|
return $this->iterator->valid(); |
62
|
|
|
} |
63
|
|
|
|
64
|
5 |
|
public function count(): int |
65
|
|
|
{ |
66
|
5 |
|
return $this->count; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|