From 8e803f1109c185fc041b0c5cb2fa66569c12dc7a Mon Sep 17 00:00:00 2001 From: fejese Date: Fri, 21 Mar 2014 17:56:09 +0100 Subject: [PATCH] Adding node name getter with tests --- src/Symfony/Component/DomCrawler/Crawler.php | 18 ++++++++++++++++++ .../Component/DomCrawler/Tests/CrawlerTest.php | 12 ++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/Symfony/Component/DomCrawler/Crawler.php b/src/Symfony/Component/DomCrawler/Crawler.php index 7d536ca52e3da..317767e85681d 100644 --- a/src/Symfony/Component/DomCrawler/Crawler.php +++ b/src/Symfony/Component/DomCrawler/Crawler.php @@ -509,6 +509,24 @@ public function attr($attribute) return $node->hasAttribute($attribute) ? $node->getAttribute($attribute) : null; } + /** + * Returns the node name of the first node of the list. + * + * @return string The node name + * + * @throws \InvalidArgumentException When current node is empty + * + * @api + */ + public function name() + { + if (!count($this)) { + throw new \InvalidArgumentException('The current node list is empty.'); + } + + return $this->getNode(0)->nodeName; + } + /** * Returns the node value of the first node of the list. * diff --git a/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php b/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php index aa3082a23eae2..06cbc8e4cf3f3 100644 --- a/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php +++ b/src/Symfony/Component/DomCrawler/Tests/CrawlerTest.php @@ -344,6 +344,18 @@ public function testMissingAttrValueIsNull() $this->assertNull($div->attr('missing-attr'), '->attr() reads missing attributes correctly'); } + public function testName() + { + $this->assertEquals('li', $this->createTestCrawler()->filterXPath('//li')->name(), '->name() returns the node name of the first element of the node list'); + + try { + $this->createTestCrawler()->filterXPath('//ol')->name(); + $this->fail('->name() throws an \InvalidArgumentException if the node list is empty'); + } catch (\InvalidArgumentException $e) { + $this->assertTrue(true, '->name() throws an \InvalidArgumentException if the node list is empty'); + } + } + public function testText() { $this->assertEquals('One', $this->createTestCrawler()->filterXPath('//li')->text(), '->text() returns the node value of the first element of the node list');