Skip to content

Commit

Permalink
Implement the iterator interface for the parser
Browse files Browse the repository at this point in the history
The parser now implements the Iterator interface, allowing parsed VCards
to be iterated over using for and foreach loops.
  • Loading branch information
wadmiraal committed Jun 1, 2016
1 parent d171336 commit 4a03d2b
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
39 changes: 38 additions & 1 deletion src/VCardParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
* Original code is available at: http://code.google.com/p/zendvcard/
*/

use Iterator;

/**
* VCard PHP Class to parse .vcard files.
*
Expand All @@ -32,7 +34,7 @@
* @author ruzicka.jan
* @author Wouter Admiraal <[email protected]>
*/
class VCardParser
class VCardParser implements Iterator
{
/**
* The raw VCard content.
Expand All @@ -48,6 +50,13 @@ class VCardParser
*/
protected $vcardObjects;

/**
* The iterator position.
*
* @var int
*/
protected $position;

/**
* Helper function to parse a file directly.
*
Expand All @@ -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.
*
Expand Down
18 changes: 18 additions & 0 deletions tests/VCardParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down

0 comments on commit 4a03d2b

Please sign in to comment.