Skip to content

Commit

Permalink
feat: method for get entity value from text
Browse files Browse the repository at this point in the history
  • Loading branch information
darkdarin committed Dec 6, 2023
1 parent 0ff0043 commit 69bdf94
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion src/DTO/MessageEntity.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,32 @@ public function __construct(
public ?User $user = null,
public ?string $language = null,
public ?string $custom_emoji_id = null,
) {}
) {
}

/**
* Correct way for get entity value from text by offset and length
*
* @see https://core.telegram.org/api/entities#entity-length
*
* @param string $text
* @return string
*/
public function getValue(string $text): string
{
$textBytes = unpack('C*', $text);
$value = [];
$offset = 0;

foreach ($textBytes as $byte) {
if ($offset >= $this->offset && $offset < $this->offset + $this->length) {
$value[] = $byte;
}
if (($byte & 0xc0) != 0x80) {
$offset += ($byte >= 0xf0 ? 2 : 1);
}
}

return pack('C*', ...$value);
}
}

0 comments on commit 69bdf94

Please sign in to comment.