Ver código fonte

[DomCrawler] added Crawler::addContent()

Fabien Potencier 15 anos atrás
pai
commit
1c0a18d1b4

+ 29 - 0
src/Symfony/Components/DomCrawler/Crawler.php

@@ -72,6 +72,35 @@ class Crawler extends \SplObjectStorage
     }
   }
 
+  public function addContent($content, $type = null)
+  {
+    if (empty($type))
+    {
+      $type = 'text/html';
+    }
+
+    // DOM only for HTML/XML content
+    if (!preg_match('/(x|ht)ml/i', $type, $matches))
+    {
+      return null;
+    }
+
+    $charset = 'ISO-8859-1';
+    if (false !== $pos = strpos($type, 'charset='))
+    {
+      $charset = substr($type, $pos + 8);
+    }
+
+    if ('x' === $matches[1])
+    {
+      $this->addXmlContent($content, $charset);
+    }
+    else
+    {
+      $this->addHtmlContent($content, $charset);
+    }
+  }
+
   /**
    * Adds an HTML content to the list of nodes.
    *

+ 26 - 0
tests/Symfony/Tests/Components/DomCrawler/CrawlerTest.php

@@ -72,6 +72,32 @@ class CrawlerTest extends \PHPUnit_Framework_TestCase
     $this->assertEquals('foo', $crawler->filter('div')->attr('class'), '->addXmlContent() adds nodes from an XML string');
   }
 
+  /**
+   * @covers Symfony\Components\DomCrawler\Crawler::addContent
+   */
+  public function testAddContent()
+  {
+    $crawler = new Crawler();
+    $crawler->addContent('<html><div class="foo"></html>', 'text/html; charset=UTF-8');
+    $this->assertEquals('foo', $crawler->filter('div')->attr('class'), '->addContent() adds nodes from an HTML string');
+
+    $crawler = new Crawler();
+    $crawler->addContent('<html><div class="foo"></html>');
+    $this->assertEquals('foo', $crawler->filter('div')->attr('class'), '->addContent() uses text/html as the default type');
+
+    $crawler = new Crawler();
+    $crawler->addContent('<html><div class="foo"></div></html>', 'text/xml; charset=UTF-8');
+    $this->assertEquals('foo', $crawler->filter('div')->attr('class'), '->addContent() adds nodes from an XML string');
+
+    $crawler = new Crawler();
+    $crawler->addContent('<html><div class="foo"></div></html>', 'text/xml');
+    $this->assertEquals('foo', $crawler->filter('div')->attr('class'), '->addContent() adds nodes from an XML string');
+
+    $crawler = new Crawler();
+    $crawler->addContent('foo bar', 'text/plain');
+    $this->assertEquals(0, $crawler->count(), '->addContent() does nothing if the type is not (x|ht)ml');
+  }
+
   /**
    * @covers Symfony\Components\DomCrawler\Crawler::addDocument
    */