Skip to content

Commit

Permalink
fix two bugs in MutableAttributedString and implement missing ArrayAc…
Browse files Browse the repository at this point in the history
…cess methods
  • Loading branch information
apemsel committed Mar 5, 2016
1 parent d0846d6 commit 14618a9
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/AttributedString.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
class AttributedString implements \Countable, \ArrayAccess
{
protected $string;
protected $attributes;
protected $attributes = [];
protected $length;
protected $byteToChar;

Expand Down
24 changes: 22 additions & 2 deletions src/MutableAttributedString.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ public function insert($pos, $string) {
*/
public function delete($pos, $length) {
$leftPart = "";
if ($pos > 0) {
$leftPart = mb_substr($this->string, 0, $pos - 1, "utf-8");
if ($pos >= 0) {
$leftPart = mb_substr($this->string, 0, $pos, "utf-8");
}

$rightPart = "";
Expand Down Expand Up @@ -113,4 +113,24 @@ protected static function mb_substr_replace($string, $replacement, $start, $leng

return join($smatches[0]);
}

// Modified ArrayAccess interface

/**
* Replace char at given offset
*
* @param int $offset offset
*/
public function offsetSet($offset, $value) {
$this->string = self::mb_substr_replace($this->string, $value, $offset, mb_strlen($value, "utf-8"));
}

/**
* Unset char at given offset
*
* @param int $offset offset
*/
public function offsetUnset($offset) {
$this->delete($offset, 1);
}
}
15 changes: 13 additions & 2 deletions test/unit/MutableAttributedStringTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public function testDelete() {

$as->setLength(0, 11, "bold");
$as->delete(4, 3);
$this->assertEquals("föö baz", $as);
$this->assertEquals("föö baz", (string) $as);
$this->assertEquals(true, $as->is("bold", 0), "start should still be bold");
$this->assertEquals(true, $as->is("bold", 6), "end should still be bold");

Expand All @@ -48,9 +48,20 @@ public function testDelete() {
$as = new MutableAttributedString("foo bar baz");

$as->setLength(0, 11, "bold");
$as->delete(8, 4);
$as->delete(7, 4);
$this->assertEquals("foo bar", $as);
$this->assertEquals(true, $as->is("bold", 0), "start should still be bold");
$this->assertEquals(true, $as->is("bold", 6), "end should still be bold");
}

public function testArrayAccess() {
$as = new MutableAttributedString("fóò bar bäz");

$as[1] = "ö";
$this->assertEquals("ö", $as[1]);
$this->assertEquals("föò bar bäz", (string) $as);

unset($as[1]);
$this->assertEquals("fò bar bäz", (string) $as);
}
}

0 comments on commit 14618a9

Please sign in to comment.