Encoder::encodeArray()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 16
rs 9.2
cc 4
eloc 11
nc 4
nop 1
1
<?php
2
3
namespace League\Torrent\Helper;
4
5
use \InvalidArgumentException;
6
7
class Encoder
8
{
9
    /**
10
     * @param $mixed
11
     *
12
     * @return string
13
     */
14
    public static function encode($mixed)
15
    {
16
        if (is_numeric($mixed)) {
17
            return self::encodeInteger($mixed);
18
        }
19
        if (is_array($mixed)) {
20
            return self::encodeArray($mixed);
21
        }
22
        if (is_string($mixed) || is_null($mixed)) {
23
            return self::encodeString((string) $mixed);
24
        }
25
26
        throw new InvalidArgumentException('Variables of type ' . gettype($mixed) . ' can not be encoded.');
27
    }
28
29
    /**
30
     * @param string $string
31
     *
32
     * @return string
33
     */
34
    public static function encodeString($string)
35
    {
36
        return strlen($string) . ':' . $string;
37
    }
38
39
    /**
40
     * @param $integer
41
     *
42
     * @return string
43
     */
44
    public static function encodeInteger($integer)
45
    {
46
        return 'i' . $integer . 'e';
47
    }
48
49
    /**
50
     * @param $array
51
     *
52
     * @return string
53
     */
54
    public static function encodeArray($array)
55
    {
56
        if (FileSystem::is_list($array)) {
57
            $return = 'l';
58
            foreach ($array as $value) {
59
                $return .= self::encode($value);
60
            }
61
        } else {
62
            ksort($array, SORT_STRING);
63
            $return = 'd';
64
            foreach ($array as $key => $value) {
65
                $return .= self::encode(strval($key)) . self::encode($value);
66
            }
67
        }
68
        return $return . 'e';
69
    }
70
}