Skip to content

Commit 394c448

Browse files
author
Frederic Massart
committed
Support for inserting an item in a CSSList
1 parent 50a802f commit 394c448

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

lib/Sabberworm/CSS/CSSList/CSSList.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,20 @@ public function append($oItem) {
3535
$this->aContents[] = $oItem;
3636
}
3737

38+
/**
39+
* Insert an item before its sibling.
40+
*
41+
* @param mixed $oItem The item.
42+
* @param mixed $oSibling The sibling.
43+
*/
44+
public function insert($oItem, $oSibling) {
45+
$iIndex = array_search($oSibling, $this->aContents);
46+
if ($iIndex === false) {
47+
return $this->append($oItem);
48+
}
49+
array_splice($this->aContents, $iIndex, 0, array($oItem));
50+
}
51+
3852
/**
3953
* Removes an item from the CSS list.
4054
* @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)

tests/Sabberworm/CSS/CSSList/DocumentTest.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Sabberworm\CSS\CSSList;
44

5+
use Sabberworm\CSS\RuleSet\DeclarationBlock;
56
use Sabberworm\CSS\Parser;
67

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

27+
public function testInsertContent() {
28+
$sCss = '.thing { left: 10px; } .stuff { margin: 1px; } ';
29+
$oParser = new Parser($sCss);
30+
$oDoc = $oParser->parse();
31+
$aContents = $oDoc->getContents();
32+
$this->assertCount(2, $aContents);
33+
34+
$oThing = $aContents[0];
35+
$oStuff = $aContents[1];
36+
37+
$oFirst = new DeclarationBlock();
38+
$oFirst->setSelectors('.first');
39+
$oBetween = new DeclarationBlock();
40+
$oBetween->setSelectors('.between');
41+
$oOrphan = new DeclarationBlock();
42+
$oOrphan->setSelectors('.forever-alone');
43+
$oNotFound = new DeclarationBlock();
44+
$oNotFound->setSelectors('.not-found');
45+
46+
$oDoc->insert($oFirst, $oThing);
47+
$oDoc->insert($oBetween, $oStuff);
48+
$oDoc->insert($oOrphan, $oNotFound);
49+
50+
$aContents = $oDoc->getContents();
51+
$this->assertCount(5, $aContents);
52+
$this->assertSame($oFirst, $aContents[0]);
53+
$this->assertSame($oThing, $aContents[1]);
54+
$this->assertSame($oBetween, $aContents[2]);
55+
$this->assertSame($oStuff, $aContents[3]);
56+
$this->assertSame($oOrphan, $aContents[4]);
57+
}
58+
2659
}

0 commit comments

Comments
 (0)