Completed
Push — master ( 1b6743...e69112 )
by Jan-Petter
9s
created

EncodingConverter::iconv()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 2
eloc 7
nc 2
nop 1
1
<?php
2
namespace vipnytt\RobotsTxtParser\Client\Encoding;
3
4
use vipnytt\RobotsTxtParser\RobotsTxtInterface;
5
6
/**
7
 * Class EncodingConverter
8
 *
9
 * @package vipnytt\RobotsTxtParser\Client\Encoding
10
 */
11
class EncodingConverter implements RobotsTxtInterface
12
{
13
    /**
14
     * String to convert
15
     * @var string
16
     */
17
    private $string;
18
19
    /**
20
     * String encoding
21
     * @var string
22
     */
23
    private $encoding;
24
25
    /**
26
     * CharacterEncodingConvert constructor.
27
     *
28
     * @param string $string
29
     * @param string $encoding
30
     */
31
    public function __construct($string, $encoding)
32
    {
33
        $this->string = $string;
34
        $this->encoding = $encoding;
35
    }
36
37
    /**
38
     * Auto mode
39
     *
40
     * @return string|false
41
     */
42
    public function auto()
43
    {
44
        if ($this->encoding == self::ENCODING) {
45
            return $this->string;
46
        } elseif (($iconv = $this->iconv()) !== false) {
47
            return $iconv;
48
        } elseif (($mbstring = $this->mbstring()) !== false) {
49
            return $mbstring;
50
        }
51
        return false;
52
    }
53
54
    /**
55
     * iconv
56
     *
57
     * @param string $outSuffix
58
     * @return string|false
59
     */
60
    public function iconv($outSuffix = '//TRANSLIT//IGNORE')
61
    {
62
        try {
63
            $converted = iconv($this->encoding, self::ENCODING . $outSuffix, $this->string);
64
        } catch (\Exception $msg) {
65
            return false;
66
        }
67
        mb_internal_encoding(self::ENCODING);
68
        return $converted;
69
    }
70
71
    /**
72
     * mbstring
73
     *
74
     * @param array|string|null $fromOverride
75
     * @return string|false
76
     */
77
    public function mbstring($fromOverride = null)
78
    {
79
        try {
80
            $converted = mb_convert_encoding($this->string, self::ENCODING, $fromOverride === null ? $this->encoding : $fromOverride);
81
        } catch (\Exception $msg) {
82
            return false;
83
        }
84
        mb_internal_encoding(self::ENCODING);
85
        return $converted;
86
    }
87
}
88