Skip to content

Commit

Permalink
Add wrapper for xpath() that always returns an array
Browse files Browse the repository at this point in the history
  • Loading branch information
danmichaelo committed Dec 16, 2014
1 parent e285c47 commit 287e5a8
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
8 changes: 8 additions & 0 deletions README.md
Expand Up @@ -74,6 +74,14 @@ Returns the first node that matches the given path, or null if none.
$node = $node->first('d:a/d:b');
```

#### all($xpath)

Returns all nodes that matches the given path, or an empty array if none.

```php
$node = $node->all('d:a/d:b');
```

#### has($xpath)

Returns true if the node exists, false if not
Expand Down
14 changes: 13 additions & 1 deletion src/Danmichaelo/QuiteSimpleXMLElement/QuiteSimpleXMLElement.php
Expand Up @@ -153,7 +153,7 @@ public function el()

/**
* @param $path
* @return array|bool|QuiteSimpleXMLElement[]
* @return bool|QuiteSimpleXMLElement[]
*/
public function xpath($path)
{
Expand All @@ -167,6 +167,18 @@ public function xpath($path)
return $r2;
}

/**
* Wrapper method for xpath() that *always* returns an array.
*
* @param $path
* @return QuiteSimpleXMLElement[]
*/
public function all($path)
{
$r = $this->xpath($path);
return (!is_array($r)) ? array() : $r;
}

public function __toString()
{
return (string) $this->el;
Expand Down
14 changes: 14 additions & 0 deletions tests/QuiteSimpleXMLElementTest.php
Expand Up @@ -219,6 +219,20 @@ public function testChildren()
$this->assertEquals('2013-09-21T18:54:39.718+02:00', $kiddo->text('ns1:DateDue'));
}

public function testAll()
{
$xml = '
<ns1:NCIPMessage xmlns:ns1="http://www.niso.org/2008/ncip">
<ns1:Test>
Hello
</ns1:Test>
</ns1:NCIPMessage>';
$dom = new QuiteSimpleXMLElement($xml);

$this->assertCount(0, $dom->all('/Test[prop="val"]'));
$this->assertCount(1, $dom->all('/ns1:NCIPMessage/ns1:Test'));
}

/**
* @expectedException Danmichaelo\QuiteSimpleXMLElement\InvalidXMLException
*/
Expand Down

0 comments on commit 287e5a8

Please sign in to comment.