Skip to content

Commit

Permalink
Fixed #13 (Enumerable::from throws InvalidArgumentException on Simple…
Browse files Browse the repository at this point in the history
…XMLElement): added support for Traversable which do not implement Iterator or IterratorAggregate (Traversable can also be implemented internally).
  • Loading branch information
Athari committed Jan 11, 2016
1 parent 26de6b4 commit bf1e9f9
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
13 changes: 13 additions & 0 deletions Tests/Unit/EnumerableTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,19 @@ function testFrom_iteratorAggregate ()
E::from(new AggregateIteratorWrapper($i))->getIterator());
}

/** @covers YaLinqo\Enumerable::from
*/
function testFrom_SimpleXMLElement ()
{
// from (SimpleXMLElement)
$this->assertEnumEquals(
[ ],
E::from(new \SimpleXMLElement('<r></r>')));
$this->assertEnumValuesEquals(
[ 'h', 'h', 'g' ],
E::from(new \SimpleXMLElement('<r><h/><h/><g/></r>'))->select('$k'));
}

/** @covers YaLinqo\Enumerable::from
* @dataProvider dataProvider_testFrom_wrongTypes
*/
Expand Down
15 changes: 12 additions & 3 deletions YaLinqo/EnumerableGeneration.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,10 @@ public static function emptyEnum ()
* <li><b>array</b>: Enumerable from ArrayIterator;
* <li><b>Enumerable</b>: Enumerable source itself;
* <li><b>Iterator</b>: Enumerable from Iterator;
* <li><b>IteratorAggregate</b>: Enumerable from Iterator returned from getIterator() method.
* <li><b>IteratorAggregate</b>: Enumerable from Iterator returned from getIterator() method;
* <li><b>Traversable</b>: Enumerable from the result of foreach over source.
* </ul>
* @param array|\Iterator|\IteratorAggregate|Enumerable $source Value to convert into Enumerable sequence.
* @param array|\Iterator|\IteratorAggregate|\Traversable|Enumerable $source Value to convert into Enumerable sequence.
* @throws \InvalidArgumentException If source is not array or Traversible or Enumerable.
* @return Enumerable
* @package YaLinqo\Generation
Expand All @@ -70,10 +71,18 @@ public static function from ($source)
$it = $source;
elseif ($source instanceof \IteratorAggregate)
$it = $source->getIterator();
elseif ($source instanceof \Traversable)
$it = self::fromTraversable($source);
if ($it !== null) {
return new self($it, false);
}
throw new \InvalidArgumentException('source must be array or Traversable or Enumerable.');
throw new \InvalidArgumentException('source must be array or Traversable.');
}

private static function fromTraversable ($source)
{
foreach ($source as $k => $v)
yield $k => $v;
}

/**
Expand Down

0 comments on commit bf1e9f9

Please sign in to comment.