1<?php
2/*
3 * This file is part of PHPUnit.
4 *
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
6 *
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
9 */
10
11/**
12 * String helpers.
13 */
14class PHPUnit_Util_String
15{
16    /**
17     * Converts a string to UTF-8 encoding.
18     *
19     * @param string $string
20     *
21     * @return string
22     */
23    public static function convertToUtf8($string)
24    {
25        return mb_convert_encoding($string, 'UTF-8');
26    }
27
28    /**
29     * Checks a string for UTF-8 encoding.
30     *
31     * @param string $string
32     *
33     * @return bool
34     */
35    protected static function isUtf8($string)
36    {
37        $length = strlen($string);
38
39        for ($i = 0; $i < $length; $i++) {
40            if (ord($string[$i]) < 0x80) {
41                $n = 0;
42            } elseif ((ord($string[$i]) & 0xE0) == 0xC0) {
43                $n = 1;
44            } elseif ((ord($string[$i]) & 0xF0) == 0xE0) {
45                $n = 2;
46            } elseif ((ord($string[$i]) & 0xF0) == 0xF0) {
47                $n = 3;
48            } else {
49                return false;
50            }
51
52            for ($j = 0; $j < $n; $j++) {
53                if ((++$i == $length) || ((ord($string[$i]) & 0xC0) != 0x80)) {
54                    return false;
55                }
56            }
57        }
58
59        return true;
60    }
61}
62