Skip to content

Commit aa2206a

Browse files
Merge pull request #42 from worksolutions/fix-iterator-behavior
Who attempts of run rewind methods is not allowed for everything iterator
2 parents 5a3faf4 + 418e373 commit aa2206a

File tree

2 files changed

+19
-29
lines changed

2 files changed

+19
-29
lines changed

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"description": "Collections library for php language",
44
"minimum-stability": "dev",
55
"license": "MIT",
6-
"version": "1.1.4",
6+
"version": "1.1.5",
77
"authors": [
88
{
99
"name": "Maxim Sokolovsky",

src/WS/Utils/Collections/CollectionFactory.php

Lines changed: 18 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -76,19 +76,20 @@ public static function fromStrict(array $values): Collection
7676
*/
7777
public static function fromIterable(iterable $iterable): Collection
7878
{
79-
if ($iterable instanceof IteratorAggregate) {
80-
/** @noinspection PhpUnhandledExceptionInspection */
81-
$iterable = $iterable->getIterator();
82-
}
83-
if (self::isStatePatternIterator($iterable)) {
84-
if (!$iterable instanceof Iterator) {
85-
throw new UnsupportedException('Only Iterator interface can be applied to IteratorCollection');
86-
}
87-
return new IteratorCollection($iterable);
88-
}
8979
$list = ArrayList::of();
80+
$count = 0;
81+
$lastItem = null;
82+
9083
foreach ($iterable as $item) {
84+
if ($count <= 1) {
85+
$isObject = is_object($item);
86+
if ($item === $lastItem && $isObject) {
87+
return self::createIterableCollection($iterable);
88+
}
89+
$lastItem = $item;
90+
}
9191
$list->add($item);
92+
$count++;
9293
}
9394

9495
return $list;
@@ -99,26 +100,15 @@ public static function empty(): Collection
99100
return ArrayList::of();
100101
}
101102

102-
private static function isStatePatternIterator(iterable $iterable): bool
103+
private static function createIterableCollection(iterable $iterable): IteratorCollection
103104
{
104-
if (!is_object($iterable)) {
105-
return false;
106-
}
107-
if (!method_exists($iterable, 'rewind')) {
108-
return false;
105+
if ($iterable instanceof IteratorAggregate) {
106+
/** @noinspection PhpUnhandledExceptionInspection */
107+
$iterable = $iterable->getIterator();
109108
}
110-
$i = 2;
111-
$lastItem = null;
112-
foreach ($iterable as $item) {
113-
if ($i === 0) {
114-
break;
115-
}
116-
if (is_object($item) && $item === $lastItem) {
117-
return true;
118-
}
119-
$lastItem = $item;
120-
$i--;
109+
if (!$iterable instanceof Iterator) {
110+
throw new UnsupportedException('Only Iterator interface can be applied to IteratorCollection');
121111
}
122-
return false;
112+
return new IteratorCollection($iterable);
123113
}
124114
}

0 commit comments

Comments
 (0)