From 394c448cc5cc36ad88ca223f4e54adbfacf9c23a Mon Sep 17 00:00:00 2001 From: Frederic Massart Date: Mon, 1 Aug 2016 19:17:17 +0800 Subject: [PATCH] Support for inserting an item in a CSSList --- lib/Sabberworm/CSS/CSSList/CSSList.php | 14 ++++++++ tests/Sabberworm/CSS/CSSList/DocumentTest.php | 33 +++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/lib/Sabberworm/CSS/CSSList/CSSList.php b/lib/Sabberworm/CSS/CSSList/CSSList.php index bc90460b..f9986eb3 100644 --- a/lib/Sabberworm/CSS/CSSList/CSSList.php +++ b/lib/Sabberworm/CSS/CSSList/CSSList.php @@ -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) diff --git a/tests/Sabberworm/CSS/CSSList/DocumentTest.php b/tests/Sabberworm/CSS/CSSList/DocumentTest.php index 00395809..ea388f9f 100644 --- a/tests/Sabberworm/CSS/CSSList/DocumentTest.php +++ b/tests/Sabberworm/CSS/CSSList/DocumentTest.php @@ -2,6 +2,7 @@ namespace Sabberworm\CSS\CSSList; +use Sabberworm\CSS\RuleSet\DeclarationBlock; use Sabberworm\CSS\Parser; class DocumentTest extends \PHPUnit_Framework_TestCase { @@ -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]); + } + }