IniBuilder   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 51.35%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 15
c 2
b 0
f 0
lcom 0
cbo 0
dl 0
loc 74
ccs 19
cts 37
cp 0.5135
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
C build() 0 38 8
B escape() 0 20 7
1
<?php
2
3
/*
4
 * This file is part of Payload.
5
 *
6
 * (c) DraperStudio <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace DraperStudio\Payload\Utils;
13
14
/**
15
 * Class IniBuilder.
16
 */
17
class IniBuilder
18
{
19
    /**
20
     * @param array $data
21
     * @param int   $depth
22
     * @param null  $prevKey
23
     *
24
     * @return string
25
     */
26 6
    public function build(array $data, $depth = 0, $prevKey = null)
27
    {
28 6
        $valueOutput = null;
29 6
        $arrayOutput = null;
30
31 6
        $position = 0;
32 6
        foreach ($data as $key => $val) {
33 6
            if (is_array($val)) {
34
                if ($depth == 0) {
35
                    $arrayOutput .= "\n[{$key}]\n";
36
                }
37
38
                $arrayOutput .= $this->build($val, $depth + 1, $key);
39
            } else {
40 6
                $valStr = $this->escape($val);
41
42 6
                if ($depth > 1) {
43
                    if ($key !== $position) {
44
                        if (ctype_digit((string) $key)) {
45
                            $position = $key;
46
                        }
47
48
                        $valueOutput .= "{$prevKey}[{$key}] = {$valStr}\n";
49
                    } else {
50
                        $valueOutput .= "{$prevKey}[] = {$valStr}\n";
51
                    }
52
53
                    ++$position;
54
                } else {
55 6
                    $valueOutput .= "{$key} = {$valStr}\n";
56
                }
57
            }
58 6
        }
59
60 6
        $output = "{$valueOutput}\n{$arrayOutput}";
61
62 6
        return $depth ? ltrim($output) : trim($output);
63
    }
64
65
    /**
66
     * @param $value
67
     *
68
     * @return mixed|string
69
     */
70 6
    public function escape($value)
71
    {
72 6
        $value = (string) $value;
73
74 6
        if (empty($value)) {
75
            return 'false';
76 6
        } elseif ($value == '1') {
77
            return 'true';
78
        }
79
80 6
        if (is_numeric($value)) {
81
            return (string) $value;
82
        }
83
84 6
        if (is_string($value) && ctype_alnum($value) && !is_numeric($value)) {
85 6
            return (string) $value;
86
        }
87
88
        return var_export($value, true);
89
    }
90
}
91