Properties   A
last analyzed

Complexity

Total Complexity 22

Size/Duplication

Total Lines 174
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 7
Bugs 4 Features 0
Metric Value
wmc 22
c 7
b 4
f 0
lcom 1
cbo 4
dl 0
loc 174
rs 10
ccs 12
cts 12
cp 1

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __toString() 0 4 1
C parseProperties() 0 60 11
A parse() 0 19 4
A getSupportedFileExtensions() 0 4 1
A loadFile() 0 10 4
A exportFormat() 0 6 1
1
<?php
2
3
/**
4
 * Konfig.
5
 *
6
 * Yet another simple configuration loader library.
7
 *
8
 * PHP version 5
9
 *
10
 * @category Library
11
 * @package  Konfig
12
 * @author   Xeriab Nabil (aka KodeBurner) <[email protected]>
13
 * @license  https://raw.github.com/xeriab/konfig/master/LICENSE MIT
14
 * @link     https://xeriab.github.io/projects/konfig
15
 */
16
17
namespace Exen\Konfig\FileParser;
18
19
use Exception;
20
use Exen\Konfig\Arr;
21
use Exen\Konfig\Utils;
22
use Exen\Konfig\Exception\ParseException;
23
24
/**
25
 * Konfig's Java-Properties parser class.
26
 *
27
 * @category FileParser
28
 * @package  Konfig
29
 * @author   Xeriab Nabil (aka KodeBurner) <[email protected]>
30
 * @license  https://raw.github.com/xeriab/konfig/master/LICENSE MIT
31
 * @link     https://xeriab.github.io/projects/konfig
32
 *
33
 * @implements Exen\Konfig\FileParser\AbstractFileParser
34
 */
35
class Properties extends AbstractFileParser
36
{
37
    /**
38
     * Parsed configuration file.
39
     *
40
     * @var array $parsedFile
41
     *
42
     * @since 0.2.5
43
     */
44
    protected $parsedFile;
45
46
    /**
47
     * Loads a PROPERTIES file as an array.
48
     *
49
     * @param string $path File path
50
     *
51
     * @throws ParseException If there is an error parsing PROPERTIES file
52
     *
53
     * @return array The parsed data
54
     *
55
     * @since 0.2.4
56
     */
57 6
    public function parse($path)
58
    {
59 6
        $this->loadFile($path);
60
61 6
        $data = $this->parsedFile;
62
63 6
        unset($this->parsedFile);
64
65 6
        if (!is_array($data) || is_null($data) || empty($data)) {
66 3
            throw new ParseException(
67
                [
68 3
                    'message' => 'Error parsing PROPERTIES file',
69 3
                    'file' => $this->file,
70
                ]
71 1
            );
72
        }
73
74 3
        return $data;
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     *
80
     * @return array Supported extensions
81
     *
82
     * @since 0.1.0
83
     */
84 3
    public function getSupportedFileExtensions()
85
    {
86 3
        return ['properties'];
87
    }
88
89
    /**
90
     * Parse Java-Properties
91
     *
92
     * @param string|null $string The string to parse
93
     *
94
     * @return             array The parsed data
95
     * @since              0.2.6
96
     * @codeCoverageIgnore
97
     */
98
    private function parseProperties($string = null)
99
    {
100
        $result = [];
101
        $lines = preg_split('/\n\t|\n/', $string);
102
        $key = '';
103
104
        static $isWaitingForOtherLine = false;
105
106
        foreach ($lines as $k => $line) {
107
            if (empty($line) || (!$isWaitingForOtherLine
108
                && strpos($line, '#') === 0)
109
            ) {
110
                continue;
111
            }
112
113
            if (!strpos($line, '=') && !$isWaitingForOtherLine) {
114
                return [];
115
            }
116
117
            if (!$isWaitingForOtherLine) {
118
                $key = substr($line, 0, strpos($line, '='));
119
                $key = trim($key);
120
                $value = substr($line, strpos($line, '=') + 1, strlen($line));
121
            } else {
122
                $value .= $line;
0 ignored issues
show
Bug introduced by
The variable $value does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
123
            }
124
125
            // Trim unnecessary white spaces
126
            $value = trim($value);
127
            $value = Utils::trimWhitespace($value);
128
129
            // Remove unnecessary double/single qoutes
130
            $value = Utils::removeQuotes($value);
131
132
            if (strpos($value, '\\') === strlen($value) - strlen('\\')) {
133
                $value = substr($value, 0, strlen($value) - 1);
134
                $isWaitingForOtherLine = true;
135
            } else {
136
                $isWaitingForOtherLine = false;
137
            }
138
139
            $result[$key] = empty($value) ? '' : $value;
140
141
            unset($lines[$k]);
142
        }
143
144
        Utils::unescapeProperties($result);
145
        Utils::trimArrayElements($result);
146
        Utils::stripBackslashes($result);
147
        Utils::fixArrayValues($result);
148
149
        // Fix for dotted properties
150
        $data = [];
151
152
        foreach ($result as $k => $v) {
153
            Arr::set($data, $k, $v);
154
        }
155
156
        return $data;
157
    }
158
159
    /**
160
     * Loads in the given file and parses it.
161
     *
162
     * @param string|bool|null $file File to load
163
     *
164
     * @return array The parsed file data
165
     *
166
     * @since              0.2.4
167
     * @codeCoverageIgnore
168
     */
169
    protected function loadFile($file = null)
170
    {
171
        $this->file = is_file($file) ? $file : false;
0 ignored issues
show
Documentation Bug introduced by
It seems like is_file($file) ? $file : false can also be of type boolean. However, the property $file is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
172
173
        $contents = $this->parseVars(Utils::getContent($this->file));
0 ignored issues
show
Bug introduced by
It seems like $this->file can also be of type boolean; however, Exen\Konfig\Utils::getContent() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
174
175
        if ($this->file && !is_null($file)) {
176
            $this->parsedFile = $this->parseProperties($contents);
177
        }
178
    }
179
180
    /**
181
     * Returns the formatted configuration file contents.
182
     *
183
     * @param array $contents configuration array
184
     *
185
     * @return string formatted configuration file contents
186
     *
187
     * @since              0.2.4
188
     * @codeCoverageIgnore
189
     */
190
    protected function exportFormat($contents = null)
191
    {
192
        throw new Exception(
193
            'Saving configuration to `Properties` is not supported at this time'
194
        );
195
    }
196
197
    /**
198
     * __toString.
199
     *
200
     * @return             string
201
     * @since              0.1.2
202
     * @codeCoverageIgnore
203
     */
204
    public function __toString()
205
    {
206
        return 'Exen\Konfig\FileParser\Properties' . PHP_EOL;
207
    }
208
}
209
210
// END OF ./src/FileParser/Properties.php FILE
211