Skip to content

Commit

Permalink
Merge pull request #5 from raqMorita/fix_encoding_issue
Browse files Browse the repository at this point in the history
Fix encoding UTF-8
  • Loading branch information
wesnick authored Oct 23, 2017
2 parents c3c902e + cc1f272 commit d0e43ad
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
37 changes: 35 additions & 2 deletions src/Wesnick/FdfUtility/FdfWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,38 @@ public function addField(PdfField $field)
$fields = $field;
}

/**
* @param string $u
*
* @return int
*/
public static function uniord($u)
{
$k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8');
$k1 = ord(substr($k, 0, 1));
$k2 = ord(substr($k, 1, 1));
return $k2 * 256 + $k1;
}

/**
* @param string $str
* @param int $l
*
* @return array
*/
public static function str_split_unicode($str, $l = 0)
{
if ($l > 0) {
$ret = [];
$len = mb_strlen($str, 'UTF-8');
for ($i = 0; $i < $len; $i += $l) {
$ret[] = mb_substr($str, $i, $l, 'UTF-8');
}
return $ret;
}
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}

/**
* @param $string
*
Expand All @@ -63,7 +95,8 @@ public static function escapePdfString($string)
{
$escaped = '';

foreach (str_split($string) as $char) {
$chars = self::str_split_unicode($string);
foreach ($chars as $char) {
switch ($ordinal = ord($char)) {
// If open paren, close paren, or backslash, escape character
case in_array($ordinal, [0x28, 0x29, 0x5c], true):
Expand All @@ -72,7 +105,7 @@ public static function escapePdfString($string)
break;
case $ordinal < 32:
case $ordinal > 126:
$escaped .= sprintf('\\%03o', $ordinal);
$escaped .= sprintf('\\%03o', self::uniord($char));
break;
default:
$escaped .= $char;
Expand Down
2 changes: 1 addition & 1 deletion tests/FdfUtility/Fields/TextFieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,6 @@ public function testDefaultValueIsRespected()
$this->assertSame('(value)', $field->getEscapedValue(), 'Default Value is ignored if value not null');

$field->setValue('');
$this->assertSame('(\)', $field->getEscapedValue(), 'Default Value is ignored if value is empty');
$this->assertSame('()', $field->getEscapedValue(), 'Default Value is ignored if value is empty');
}
}

0 comments on commit d0e43ad

Please sign in to comment.