@@ -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 null or an exception.
59
+ *
60
+ * @var bool
61
61
*/
62
- public function __construct ($ node = null , string $ uri = null , string $ baseHref = null )
62
+ private $ nullOnValue ;
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 $nullOnValue Return null on text and html value instead of an exception
69
+ */
70
+ public function __construct ($ node = null , string $ uri = null , string $ baseHref = null , bool $ nullOnValue = false )
63
71
{
64
72
$ this ->uri = $ uri ;
65
73
$ this ->baseHref = $ baseHref ?: $ uri ;
74
+ $ this ->nullOnValue = $ nullOnValue ;
66
75
67
76
$ this ->add ($ node );
68
77
}
@@ -570,13 +579,15 @@ public function nodeName()
570
579
/**
571
580
* Returns the node value of the first node of the list.
572
581
*
573
- * @return string The node value
574
- *
575
- * @throws \InvalidArgumentException When current node is empty
582
+ * @return string|null The node value or null when current node is empty
576
583
*/
577
584
public function text ()
578
585
{
579
586
if (!$ this ->nodes ) {
587
+ if ($ this ->nullOnValue ) {
588
+ return null ;
589
+ }
590
+
580
591
throw new \InvalidArgumentException ('The current node list is empty. ' );
581
592
}
582
593
@@ -586,13 +597,15 @@ public function text()
586
597
/**
587
598
* Returns the first node of the list as HTML.
588
599
*
589
- * @return string The node html
590
- *
591
- * @throws \InvalidArgumentException When current node is empty
600
+ * @return string|null The node html or null when current node is empty
592
601
*/
593
602
public function html ()
594
603
{
595
604
if (!$ this ->nodes ) {
605
+ if ($ this ->nullOnValue ) {
606
+ return null ;
607
+ }
608
+
596
609
throw new \InvalidArgumentException ('The current node list is empty. ' );
597
610
}
598
611
@@ -1152,7 +1165,7 @@ private function findNamespacePrefixes(string $xpath): array
1152
1165
*/
1153
1166
private function createSubCrawler ($ nodes )
1154
1167
{
1155
- $ crawler = new static ($ nodes , $ this ->uri , $ this ->baseHref );
1168
+ $ crawler = new static ($ nodes , $ this ->uri , $ this ->baseHref , $ this -> nullOnValue );
1156
1169
$ crawler ->isHtml = $ this ->isHtml ;
1157
1170
$ crawler ->document = $ this ->document ;
1158
1171
$ crawler ->namespaces = $ this ->namespaces ;
0 commit comments