[DomCrawler] Attach label to form fields

This commit is contained in:
Carlos Ortega Huetos 2016-03-26 16:23:08 +00:00 committed by Fabien Potencier
parent 3c75c48838
commit 82ef55b976
2 changed files with 58 additions and 0 deletions

View File

@ -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.
*

View File

@ -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');
}
}