Skip to content

Commit

Permalink
added function utf8_safe_encode
Browse files Browse the repository at this point in the history
  • Loading branch information
[email protected] authored and [email protected] committed Dec 30, 2023
1 parent 9be157f commit 370f848
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/PhPease/String/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,30 @@ function random_string(int $length = 10, string $token = null): string
}
return $string;
}

/**
* @param $str
* @return bool
*/
function is_utf8_encoded($str): bool
{
if (function_exists('mb_check_encoding')) {
return mb_check_encoding($str, 'UTF-8');
}
return preg_match('//u', $str) !== false;
}

/**
* @param $str
* @return mixed|string
*/
function utf8_safe_encode($str) {
if (!is_utf8_encoded($str)) {
if (function_exists('mb_convert_encoding')) {
$str = mb_convert_encoding($str, 'UTF-8', 'auto');
} elseif (function_exists('utf8_encode')) {
$str = utf8_encode($str);
}
}
return $str;
}
21 changes: 21 additions & 0 deletions tests/StringTest.php
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
use function PhPease\String\is_utf8_encoded;
use function PhPease\String\random_string;
use function PhPease\String\str_contains;
use function PhPease\String\str_ends_with;
use function PhPease\String\str_replace_all_except_numbers;
use function PhPease\String\str_starts_with;
use function PhPease\String\to_camel_case;
use function PhPease\String\utf8_safe_encode;
use function PhPease\Variable\is_stricly_true;
use function PhPease\Variable\is_true;
use function PhPease\Variable\is_stricly_false;
Expand Down Expand Up @@ -82,4 +84,23 @@ public function testRandomString()
$this->expectException(\TypeError::class);
$this->assertEquals(0, strlen(random_string(PHP_INT_MIN - 1)));
}

public function testStrIsUtf8EncodedWithValidUtf8String()
{
$string = "Fédération Camerounaise de Football";
$encodedString = utf8_safe_encode($string);

$this->assertTrue(is_utf8_encoded($encodedString));
}

public function testStrIsUtf8EncodedWithInvalidUtf8String()
{
$string = "\xC3\x28";

$this->assertFalse(is_utf8_encoded($string));

$encodedString = utf8_safe_encode($string);

$this->assertTrue(is_utf8_encoded($encodedString));
}
}

0 comments on commit 370f848

Please sign in to comment.