Completed
Push — main ( a6c50a...7d728f )
by Mauro
32s queued 16s
created

Emoji::generateMap()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Matecat\EmojiParser;
4
5
class Emoji {
6
7
    private static $chmap            = [];
8
    private static $inverse_char_map = [];
9
10
    /**
11
     * Generate the char map
12
     */
13
    private static function generateMap() {
14
        if ( empty( self::$chmap ) ) {
15
            self::$chmap = include_once 'chmap.php';
16
        }
17
    }
18
19
    /**
20
     * Generate the inverse char map
21
     */
22
    private static function generateReverseMap() {
23
        self::generateMap();
24
25
        if ( empty( self::$inverse_char_map ) ) {
26
            self::$inverse_char_map = array_flip( self::$chmap );
27
        }
28
    }
29
30
    /**
31
     * @param $str
32
     *
33
     * @return string
34
     */
35
    public static function toEntity( $str ) {
36
        self::generateMap();
37
        $letters = preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY );
38
39
        foreach ( $letters as $letter ) {
40
            if ( isset ( self::$chmap[ $letter ] ) ) {
41
                $str = str_replace( $letter, self::$chmap[ $letter ], $str );
42
            }
43
        }
44
45
        return $str;
46
    }
47
48
    /**
49
     * @param $str
50
     *
51
     * @return string
52
     */
53
    public static function toEmoji( $str ) {
54
        self::generateReverseMap();
55
        preg_match_all( '/&#[0-9a-fA-F]+;/', $str, $emoji_entity_list, PREG_PATTERN_ORDER );
56
57
        foreach ( $emoji_entity_list[ 0 ] as $emoji_entity ) {
58
            if ( array_key_exists( $emoji_entity, self::$inverse_char_map ) ) {
59
                $str = str_replace( $emoji_entity, self::$inverse_char_map[ $emoji_entity ], $str );
60
            }
61
        }
62
63
        return $str;
64
    }
65
66
}