@@ -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