diff --git a/Tests/Unit/EnumerableTest.php b/Tests/Unit/EnumerableTest.php index a76ca46..ff64ed3 100644 --- a/Tests/Unit/EnumerableTest.php +++ b/Tests/Unit/EnumerableTest.php @@ -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(''))); + $this->assertEnumValuesEquals( + [ 'h', 'h', 'g' ], + E::from(new \SimpleXMLElement(''))->select('$k')); + } + /** @covers YaLinqo\Enumerable::from * @dataProvider dataProvider_testFrom_wrongTypes */ diff --git a/YaLinqo/EnumerableGeneration.php b/YaLinqo/EnumerableGeneration.php index 279c70c..30eb385 100644 --- a/YaLinqo/EnumerableGeneration.php +++ b/YaLinqo/EnumerableGeneration.php @@ -52,9 +52,10 @@ public static function emptyEnum () *
  • array: Enumerable from ArrayIterator; *
  • Enumerable: Enumerable source itself; *
  • Iterator: Enumerable from Iterator; - *
  • IteratorAggregate: Enumerable from Iterator returned from getIterator() method. + *
  • IteratorAggregate: Enumerable from Iterator returned from getIterator() method; + *
  • Traversable: Enumerable from the result of foreach over source. * - * @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 @@ -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; } /**