From 83ee3e48c9fbc91d66af9c9638f97f21a454493d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Cholewa?= Date: Thu, 21 Feb 2019 08:16:06 +0100 Subject: [PATCH] fix for trimmed values labels multibyte chars --- src/Sav/Record/ValueLabel.php | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/Sav/Record/ValueLabel.php b/src/Sav/Record/ValueLabel.php index 640a540..f0aa8a6 100644 --- a/src/Sav/Record/ValueLabel.php +++ b/src/Sav/Record/ValueLabel.php @@ -108,16 +108,22 @@ public function write(Buffer $buffer) $buffer->writeInt(self::TYPE); $buffer->writeInt(count($this->labels)); foreach ($this->labels as $item) { - $labelLength = mb_strlen($item['label']); - $labelLength = min($labelLength, self::LABEL_MAX_LENGTH); + $labelLength = min(mb_strlen($item['label']), self::LABEL_MAX_LENGTH); + $label = mb_substr($item['label'], 0, $labelLength); + $labelLengthBytes = mb_strlen($label, '8bit'); + while ($labelLengthBytes > 255) { + // Strip one char, can be multiple bytes + $label = mb_substr($item['label'], 0, -1); + $labelLengthBytes = mb_strlen($label, '8bit'); + } if ($convertToDouble) { $item['value'] = Utils::stringToDouble($item['value']); } $buffer->writeDouble($item['value']); - $buffer->write(chr($labelLength)); - $buffer->writeString($item['label'], Utils::roundUp($labelLength + 1, 8) - 1); + $buffer->write(chr($labelLengthBytes)); + $buffer->writeString($label, Utils::roundUp($labelLengthBytes + 1, 8) - 1); } // Value label variable record.