@@ -55,14 +55,23 @@ class Crawler implements \Countable, \IteratorAggregate
55
55
private $ isHtml = true ;
56
56
57
57
/**
58
- * @param mixed $node A Node to use as the base for the crawling
59
- * @param string $uri The current URI
60
- * @param string $baseHref The base href value
58
+ * Whether the text() and html() methods will return an empty string
59
+ *
60
+ * @var bool
61
61
*/
62
- public function __construct ($ node = null , string $ uri = null , string $ baseHref = null )
62
+ private $ emptyValue ;
63
+
64
+ /**
65
+ * @param mixed $node A Node to use as the base for the crawling
66
+ * @param string $uri The current URI
67
+ * @param string $baseHref The base href value
68
+ * @param bool $emptyValue Return empty string on text and html methods instead of an exception
69
+ */
70
+ public function __construct ($ node = null , string $ uri = null , string $ baseHref = null , bool $ emptyValue = false )
63
71
{
64
72
$ this ->uri = $ uri ;
65
73
$ this ->baseHref = $ baseHref ?: $ uri ;
74
+ $ this ->emptyValue = $ emptyValue ;
66
75
67
76
$ this ->add ($ node );
68
77
}
@@ -571,12 +580,15 @@ public function nodeName()
571
580
* Returns the node value of the first node of the list.
572
581
*
573
582
* @return string The node value
574
- *
575
- * @throws \InvalidArgumentException When current node is empty
583
+ * @throws \InvalidArgumentException When current node is empty unless the emptyValue option is set
576
584
*/
577
585
public function text ()
578
586
{
579
587
if (!$ this ->nodes ) {
588
+ if ($ this ->emptyValue ) {
589
+ return '' ;
590
+ }
591
+
580
592
throw new \InvalidArgumentException ('The current node list is empty. ' );
581
593
}
582
594
@@ -587,12 +599,15 @@ public function text()
587
599
* Returns the first node of the list as HTML.
588
600
*
589
601
* @return string The node html
590
- *
591
- * @throws \InvalidArgumentException When current node is empty
602
+ * @throws \InvalidArgumentException When current node is empty unless the emptyValue option is set
592
603
*/
593
604
public function html ()
594
605
{
595
606
if (!$ this ->nodes ) {
607
+ if ($ this ->emptyValue ) {
608
+ return '' ;
609
+ }
610
+
596
611
throw new \InvalidArgumentException ('The current node list is empty. ' );
597
612
}
598
613
@@ -1152,7 +1167,7 @@ private function findNamespacePrefixes(string $xpath): array
1152
1167
*/
1153
1168
private function createSubCrawler ($ nodes )
1154
1169
{
1155
- $ crawler = new static ($ nodes , $ this ->uri , $ this ->baseHref );
1170
+ $ crawler = new static ($ nodes , $ this ->uri , $ this ->baseHref , $ this -> emptyValue );
1156
1171
$ crawler ->isHtml = $ this ->isHtml ;
1157
1172
$ crawler ->document = $ this ->document ;
1158
1173
$ crawler ->namespaces = $ this ->namespaces ;
0 commit comments