Skip to content

Commit

Permalink
Add unwrap() function.
Browse files Browse the repository at this point in the history
  • Loading branch information
joshua-graham-adelphi committed Nov 4, 2021
1 parent 3b0dba3 commit ae6a062
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ DomQuery::create('<a title="hello"></a>')->attr('title') // hello
- `.wrap( [content] )`
- `.wrapAll( [content] )`
- `.wrapInner( [content] )`
- `.unwrap( )`
- `.remove( [selector] )`

<sub>\* __[content]__ can be html or an instance of DomQuery|DOMNodeList|DOMNode</sub>
Expand Down
20 changes: 20 additions & 0 deletions src/Rct567/DomQuery/DomQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -1283,6 +1283,26 @@ public function addBack()
return $this;
}

/**
* Unwrap all the the matched elements.
*
* @return $this
*/
public function unwrap()
{
foreach ($this as $node) {
$parent = $node->parent();
// Replace parent node (the one we're unwrapping) with it's children.
foreach ($parent->contents() as $childNode) {
$oldChildNode = $childNode->clone();
$childNode->remove();
$parent->before($oldChildNode);
}
$parent->remove();
}
return $this;
}

/**
* Check if property exist for this instance
*
Expand Down
30 changes: 30 additions & 0 deletions tests/Rct567/DomQuery/Tests/DomQueryManipulationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,36 @@ public function testWrapWithMultipleElementsWrapper()
$this->assertEquals("<p><div><x><a>Hello</a></x></div></p>", (string) $dom);
}

/*
* Test unwrap.
*/
public function testUnwrap()
{
$expected = '<html><body><a href="http://example.org/">this is a test</a></body></html>';
$doc = DomQuery::create('<html><body><article><a href="http://example.org/">this is a test</a></article></body></html>');
$doc->find('article > a')->first()->unwrap();
$this->assertEquals($expected, (string) $dom);
}

/*
* Test wraping and unwrapping.
*/
public function testWrapAllandUnwrap()
{
$input = '<div>' . PHP_EOL .
' <div id="target" class="my-class">' . PHP_EOL .
' <div class="nested-class">' . PHP_EOL .
' <span class="my-span"></span>' . PHP_EOL .
' </div>' . PHP_EOL .
' <div class="nested-class">' . PHP_EOL .
' <span class="my-span"></span>' . PHP_EOL .
' </div>' . PHP_EOL .
' </div>' . PHP_EOL .
'</div>';
$dom->find('#target')->wrapAll('<div id="extra-wrap"></div>')->parent()->children()->unwrap();
$this->assertEquals($input, (string) $dom);
}

/*
* Test remove
*/
Expand Down

0 comments on commit ae6a062

Please sign in to comment.