Completed
Branch 2.0-dev (131e57)
by Jan-Petter
02:08
created

CharacterEncodingConvert   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 77
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 10
c 1
b 0
f 0
lcom 1
cbo 0
dl 0
loc 77
rs 10

4 Methods

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