Add getAttributeValueByTagName to dom helper
I'm adding this method to cover use-cases where we need to extract classes from a block's HTML. [MAILPOET-5741]
This commit is contained in:
committed by
Rostislav Wolný
parent
875fde56e9
commit
d35e498f36
@@ -33,6 +33,17 @@ class DomDocumentHelper {
|
||||
return $element->hasAttribute($attribute) ? $element->getAttribute($attribute) : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for the first appearance of the given tag name and returns the value of specified attribute.
|
||||
*/
|
||||
public function getAttributeValueByTagName(string $tagName, string $attribute): ?string {
|
||||
$element = $this->findElement($tagName);
|
||||
if (!$element) {
|
||||
return null;
|
||||
}
|
||||
return $this->getAttributeValue($element, $attribute);
|
||||
}
|
||||
|
||||
public function getOuterHtml(\DOMElement $element): string {
|
||||
return (string)$this->dom->saveHTML($element);
|
||||
}
|
||||
|
@@ -37,4 +37,11 @@ class DomDocumentHelperTest extends \MailPoetUnitTest {
|
||||
$this->assertInstanceOf(\DOMElement::class, $element);
|
||||
$this->assertEquals('<img src="https://test.com/DALL%C2%B7E-A%C2%AE%E2%88%91oecas%C6%92-803x1024.jpg">', $domDocumentHelper->getOuterHtml($element));
|
||||
}
|
||||
|
||||
public function testItGetsAttributeValueByTagName(): void {
|
||||
$html = '<div><p class="some-class">Some text</p><p class="second-paragraph"></p></div>';
|
||||
$domDocumentHelper = new DomDocumentHelper($html);
|
||||
$this->assertEquals('some-class', $domDocumentHelper->getAttributeValueByTagName('p', 'class'));
|
||||
$this->assertNull($domDocumentHelper->getAttributeValueByTagName('span', 'class'));
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user