Skip to content

Commit

Permalink
Refactor line length calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
olivervogel committed May 8, 2024
1 parent 7f33feb commit 193324e
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 4 deletions.
14 changes: 12 additions & 2 deletions src/Typography/Line.php
Expand Up @@ -86,15 +86,25 @@ public function setPosition(Point $point): self
}

/**
* Count segments of line
*
* Count segments (individual words including punctuation marks) of line
*
* @return int
*/
public function count(): int
{
return count($this->segments);
}

/**
* Count characters of line
*
* @return int
*/
public function length(): int
{
return mb_strlen((string) $this);
}

/**
* Cast line to string
*
Expand Down
4 changes: 2 additions & 2 deletions src/Typography/TextBlock.php
Expand Up @@ -62,10 +62,10 @@ public function longestLine(): Line
{
$lines = $this->lines();
usort($lines, function (Line $a, Line $b) {
if (mb_strlen((string) $a) === mb_strlen((string) $b)) {
if ($a->length() === $b->length()) {
return 0;
}
return mb_strlen((string) $a) > mb_strlen((string) $b) ? -1 : 1;
return $a->length() > $b->length() ? -1 : 1;
});

return $lines[0];
Expand Down
15 changes: 15 additions & 0 deletions tests/Unit/Typography/LineTest.php
Expand Up @@ -45,6 +45,21 @@ public function testCount(): void
$this->assertEquals(2, $line->count());
}

public function testLength(): void
{
$line = new Line();
$this->assertEquals(0, $line->length());

$line = new Line("foo");
$this->assertEquals(3, $line->length());

$line = new Line("foo bar.");
$this->assertEquals(8, $line->length());

$line = new Line("🫷🙂🫸");
$this->assertEquals(3, $line->length());
}

public function testAdd(): void
{
$line = new Line();
Expand Down

0 comments on commit 193324e

Please sign in to comment.