Skip to content

Support for inserting an item in a CSSList #115

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions lib/Sabberworm/CSS/CSSList/CSSList.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ public function append($oItem) {
$this->aContents[] = $oItem;
}

/**
* Insert an item before its sibling.
*
* @param mixed $oItem The item.
* @param mixed $oSibling The sibling.
*/
public function insert($oItem, $oSibling) {
$iIndex = array_search($oSibling, $this->aContents);
if ($iIndex === false) {
return $this->append($oItem);
}
array_splice($this->aContents, $iIndex, 0, array($oItem));
}

/**
* Removes an item from the CSS list.
* @param RuleSet|Import|Charset|CSSList $oItemToRemove May be a RuleSet (most likely a DeclarationBlock), a Import, a Charset or another CSSList (most likely a MediaQuery)
Expand Down
33 changes: 33 additions & 0 deletions tests/Sabberworm/CSS/CSSList/DocumentTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Sabberworm\CSS\CSSList;

use Sabberworm\CSS\RuleSet\DeclarationBlock;
use Sabberworm\CSS\Parser;

class DocumentTest extends \PHPUnit_Framework_TestCase {
Expand All @@ -23,4 +24,36 @@ public function testOverrideContents() {
$this->assertCount(2, $aFinalContents);
}

public function testInsertContent() {
$sCss = '.thing { left: 10px; } .stuff { margin: 1px; } ';
$oParser = new Parser($sCss);
$oDoc = $oParser->parse();
$aContents = $oDoc->getContents();
$this->assertCount(2, $aContents);

$oThing = $aContents[0];
$oStuff = $aContents[1];

$oFirst = new DeclarationBlock();
$oFirst->setSelectors('.first');
$oBetween = new DeclarationBlock();
$oBetween->setSelectors('.between');
$oOrphan = new DeclarationBlock();
$oOrphan->setSelectors('.forever-alone');
$oNotFound = new DeclarationBlock();
$oNotFound->setSelectors('.not-found');

$oDoc->insert($oFirst, $oThing);
$oDoc->insert($oBetween, $oStuff);
$oDoc->insert($oOrphan, $oNotFound);

$aContents = $oDoc->getContents();
$this->assertCount(5, $aContents);
$this->assertSame($oFirst, $aContents[0]);
$this->assertSame($oThing, $aContents[1]);
$this->assertSame($oBetween, $aContents[2]);
$this->assertSame($oStuff, $aContents[3]);
$this->assertSame($oOrphan, $aContents[4]);
}

}