1
0
mirror of https://github.com/Intervention/image.git synced 2025-01-17 12:18:14 +01:00

Refactor line length calculation

This commit is contained in:
Oliver Vogel 2024-05-08 15:53:15 +02:00
parent 7f33feb743
commit 193324ec88
No known key found for this signature in database
GPG Key ID: 1B19D214C02D69BB
3 changed files with 29 additions and 4 deletions

View File

@ -86,8 +86,8 @@ class Line implements IteratorAggregate, Countable
}
/**
* Count segments of line
*
* Count segments (individual words including punctuation marks) of line
*
* @return int
*/
public function count(): int
@ -95,6 +95,16 @@ class Line implements IteratorAggregate, Countable
return count($this->segments);
}
/**
* Count characters of line
*
* @return int
*/
public function length(): int
{
return mb_strlen((string) $this);
}
/**
* Cast line to string
*

View File

@ -62,10 +62,10 @@ class TextBlock extends Collection
{
$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];

View File

@ -45,6 +45,21 @@ final class LineTest extends BaseTestCase
$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();