Skip to content

Commit 193324e

Browse files
committed
Refactor line length calculation
1 parent 7f33feb commit 193324e

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

src/Typography/Line.php

+12-2
Original file line numberDiff line numberDiff line change
@@ -86,15 +86,25 @@ public function setPosition(Point $point): self
8686
}
8787

8888
/**
89-
* Count segments of line
90-
*
89+
* Count segments (individual words including punctuation marks) of line
90+
*
9191
* @return int
9292
*/
9393
public function count(): int
9494
{
9595
return count($this->segments);
9696
}
9797

98+
/**
99+
* Count characters of line
100+
*
101+
* @return int
102+
*/
103+
public function length(): int
104+
{
105+
return mb_strlen((string) $this);
106+
}
107+
98108
/**
99109
* Cast line to string
100110
*

src/Typography/TextBlock.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,10 @@ public function longestLine(): Line
6262
{
6363
$lines = $this->lines();
6464
usort($lines, function (Line $a, Line $b) {
65-
if (mb_strlen((string) $a) === mb_strlen((string) $b)) {
65+
if ($a->length() === $b->length()) {
6666
return 0;
6767
}
68-
return mb_strlen((string) $a) > mb_strlen((string) $b) ? -1 : 1;
68+
return $a->length() > $b->length() ? -1 : 1;
6969
});
7070

7171
return $lines[0];

tests/Unit/Typography/LineTest.php

+15
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,21 @@ public function testCount(): void
4545
$this->assertEquals(2, $line->count());
4646
}
4747

48+
public function testLength(): void
49+
{
50+
$line = new Line();
51+
$this->assertEquals(0, $line->length());
52+
53+
$line = new Line("foo");
54+
$this->assertEquals(3, $line->length());
55+
56+
$line = new Line("foo bar.");
57+
$this->assertEquals(8, $line->length());
58+
59+
$line = new Line("🫷🙂🫸");
60+
$this->assertEquals(3, $line->length());
61+
}
62+
4863
public function testAdd(): void
4964
{
5065
$line = new Line();

0 commit comments

Comments
 (0)