From 4a03d2b0bc4d8074164ce86cdee063814ac491e8 Mon Sep 17 00:00:00 2001 From: Wouter Admiraal Date: Wed, 1 Jun 2016 15:39:23 +0200 Subject: [PATCH] Implement the iterator interface for the parser The parser now implements the Iterator interface, allowing parsed VCards to be iterated over using for and foreach loops. --- src/VCardParser.php | 39 ++++++++++++++++++++++++++++++++++++++- tests/VCardParserTest.php | 18 ++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/src/VCardParser.php b/src/VCardParser.php index 6c86855..059b0f3 100644 --- a/src/VCardParser.php +++ b/src/VCardParser.php @@ -21,6 +21,8 @@ * Original code is available at: http://code.google.com/p/zendvcard/ */ +use Iterator; + /** * VCard PHP Class to parse .vcard files. * @@ -32,7 +34,7 @@ * @author ruzicka.jan * @author Wouter Admiraal */ -class VCardParser +class VCardParser implements Iterator { /** * The raw VCard content. @@ -48,6 +50,13 @@ class VCardParser */ protected $vcardObjects; + /** + * The iterator position. + * + * @var int + */ + protected $position; + /** * Helper function to parse a file directly. * @@ -68,9 +77,37 @@ public function __construct($content) { $this->content = $content; $this->vcardObjects = array(); + $this->rewind(); $this->parse(); } + public function rewind() + { + $this->position = 0; + } + + public function current() + { + if ($this->valid()) { + return $this->getCardAtIndex($this->position); + } + } + + public function key() + { + return $this->position; + } + + public function next() + { + $this->position++; + } + + public function valid() + { + return !empty($this->vcardObjects[$this->position]); + } + /** * Fetch all the imported VCards. * diff --git a/tests/VCardParserTest.php b/tests/VCardParserTest.php index ea633bb..3cff9ff 100644 --- a/tests/VCardParserTest.php +++ b/tests/VCardParserTest.php @@ -199,6 +199,24 @@ public function testVcardDB() $this->assertEquals($parser->getCardAtIndex(1)->fullname, "Ipsum Lorem"); } + public function testIteration() + { + // Prepare a VCard DB. + $db = ''; + $vcard = new VCard(); + $vcard->addName("Admiraal", "Wouter"); + $db .= $vcard->buildVCard(); + + $vcard = new VCard(); + $vcard->addName("Lorem", "Ipsum"); + $db .= $vcard->buildVCard(); + + $parser = new VCardParser($db); + foreach ($parser as $i => $card) { + $this->assertEquals($card->fullname, $i == 0 ? "Wouter Admiraal" : "Ipsum Lorem"); + } + } + public function testFromFile() { $parser = VCardParser::parseFromFile(__DIR__ . '/example.vcf');