[DomCrawler] Attach label to form fields
This commit is contained in:
parent
3c75c48838
commit
82ef55b976
|
@ -57,6 +57,30 @@ abstract class FormField
|
|||
$this->initialize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the label tag associated to the field or null if none.
|
||||
*
|
||||
* @return \DOMElement|null
|
||||
*/
|
||||
public function getLabel()
|
||||
{
|
||||
$xpath = new \DOMXPath($this->node->ownerDocument);
|
||||
|
||||
if ($this->node->hasAttribute('id')) {
|
||||
$labels = $xpath->query(sprintf('descendant::label[@for="%s"]', $this->node->getAttribute('id')));
|
||||
if ($labels->length > 0) {
|
||||
return $labels->item(0);
|
||||
}
|
||||
}
|
||||
|
||||
$labels = $xpath->query('ancestor::label[1]', $this->node);
|
||||
if ($labels->length > 0) {
|
||||
return $labels->item(0);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the field.
|
||||
*
|
||||
|
|
|
@ -35,4 +35,38 @@ class FormFieldTest extends FormFieldTestCase
|
|||
|
||||
$this->assertTrue($field->hasValue(), '->hasValue() always returns true');
|
||||
}
|
||||
|
||||
public function testLabelReturnsNullIfNoneIsDefined()
|
||||
{
|
||||
$dom = new \DOMDocument();
|
||||
$dom->loadHTML('<html><form><input type="text" id="foo" name="foo" value="foo" /><input type="submit" /></form></html>');
|
||||
|
||||
$field = new InputFormField($dom->getElementById('foo'));
|
||||
$this->assertNull($field->getLabel(), '->getLabel() returns null if no label is defined');
|
||||
}
|
||||
|
||||
public function testLabelIsAssignedByForAttribute()
|
||||
{
|
||||
$dom = new \DOMDocument();
|
||||
$dom->loadHTML('<html><form>
|
||||
<label for="foo">Foo label</label>
|
||||
<input type="text" id="foo" name="foo" value="foo" />
|
||||
<input type="submit" />
|
||||
</form></html>');
|
||||
|
||||
$field = new InputFormField($dom->getElementById('foo'));
|
||||
$this->assertEquals('Foo label', $field->getLabel()->textContent, '->getLabel() returns the associated label');
|
||||
}
|
||||
|
||||
public function testLabelIsAssignedByParentingRelation()
|
||||
{
|
||||
$dom = new \DOMDocument();
|
||||
$dom->loadHTML('<html><form>
|
||||
<label for="foo">Foo label<input type="text" id="foo" name="foo" value="foo" /></label>
|
||||
<input type="submit" />
|
||||
</form></html>');
|
||||
|
||||
$field = new InputFormField($dom->getElementById('foo'));
|
||||
$this->assertEquals('Foo label', $field->getLabel()->textContent, '->getLabel() returns the parent label');
|
||||
}
|
||||
}
|
||||
|
|
Reference in New Issue