Completed
Push — master ( f947b6...a9fbef )
by Xeriab
04:30
created

Properties   B

Complexity

Total Complexity 52

Size/Duplication

Total Lines 317
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 52
c 1
b 1
f 0
lcom 1
cbo 4
dl 0
loc 317
ccs 11
cts 11
cp 1
rs 7.9487

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getSupportedFileExtensions() 0 4 1
A parse() 0 19 2
F parseProperties() 0 145 34
A unescapeProperties() 0 8 2
A deleteFields() 0 10 3
A getProperties() 0 17 4
A loadFile() 0 10 4
A exportFormat() 0 6 1
A __toString() 0 4 1

How to fix   Complexity   

Complex Class

Complex classes like Properties often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Properties, and based on these observations, apply Extract Interface, too.

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
 * Properties
26
 * Konfig's Java-Properties parser class.
27
 *
28
 * @category FileParser
29
 * @package  Konfig
30
 * @author   Xeriab Nabil (aka KodeBurner) <[email protected]>
31
 * @license  https://raw.github.com/xeriab/konfig/master/LICENSE MIT
32
 * @link     https://xeriab.github.io/projects/konfig
33
 *
34
 * @implements Exen\Konfig\FileParser\AbstractFileParser
35
 */
36
class Properties extends AbstractFileParser
37
{
38
    /**
39
     * Loads a PROPERTIES file as an array.
40
     *
41
     * @param string $path File path
42
     *
43
     * @throws ParseException If there is an error parsing PROPERTIES file
44
     *
45
     * @return array The parsed data
46
     *
47
     * @since 0.2.4
48
     */
49
    public function parse($path)
50
    {
51 6
        $data = null;
52
53 6
        $this->loadFile($path);
54
55 6
        try {
56
            $data = $this->getProperties();
57 6
        } catch (Exception $ex) {
58 3
            throw new ParseException(
59
                [
60 3
                    'message' => 'Error parsing PROPERTIES file',
61 3
                    'exception' => $ex
62
                ]
63 2
            );
64
        }
65
66 3
        return $data;
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     *
72
     * @return array Supported extensions
73
     *
74
     * @since 0.1.0
75
     */
76 3
    public function getSupportedFileExtensions()
77
    {
78 3
        return ['properties'];
79
    }
80
81
    /**
82
     * Parse Java-Properties
83
     *
84
     * @return             array The parsed data
85
     * @since              0.2.6
86
     * @codeCoverageIgnore
87
     */
88
    private function parseProperties()
89
    {
90
        $analysis = [];
91
92
        static $isWaitingForOtherLine = false;
93
94
        foreach ($this->parsedFile as $lineNb => $line) {
0 ignored issues
show
Bug introduced by
The expression $this->parsedFile of type string is not traversable.
Loading history...
95
            $ifl = array_flip(array_keys($this->parsedFile))[$lineNb] + 1;
96
97
            if ((empty($line) || is_null($line)) && !$isWaitingForOtherLine) {
98
                $analysis[$lineNb] = ['emptyline', null, 'line' => $ifl];
99
                continue;
100
            }
101
102
            if (!$isWaitingForOtherLine && Utils::stringStart('#', $line)) {
103
                $analysis[$lineNb] = [
104
                    'comment',
105
                    trim(substr($line, 0)),
106
                    'line' => $ifl
107
                ];
108
109
                continue;
110
            }
111
112
            // Property name, check for escaped equal sign
113
            if (substr_count($line, '=') > substr_count($line, '\=')) {
114
                $temp = explode('=', $line, 2);
115
                $temp = Utils::trimArrayElements($temp);
116
117
                if (count($temp) === 2) {
118
                    $temp[1] = Utils::removeQuotes($temp[1]);
119
                    $analysis[$lineNb] = [
120
                        'property',
121
                        $temp[0],
122
                        $temp[1],
123
                        'line' => $ifl
124
                    ];
125
                }
126
127
                unset($temp);
128
129
                continue;
130
            } else {
131
                throw new Exception('Wrong Configuration');
132
                // break;
133
            }
134
135
            // Multiline data
136
            if (substr_count($line, '=') === 0) {
0 ignored issues
show
Unused Code introduced by
// Multiline data if (su... $ifl); continue; } does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
137
                $analysis[$lineNb] = ['multiline', null, $line, 'line' => $ifl];
138
                continue;
139
            }
140
        }
141
142
        // Second pass, we associate comments to entities
143
        $counter = Utils::getNumberLinesMatching('comment', $analysis);
144
145
        while ($counter > 0) {
146
            foreach ($analysis as $lineNb => $line) {
147
                if ($line[0] === 'comment'
148
                    && isset($analysis[$lineNb + 1][0])
149
                    && $analysis[$lineNb + 1][0] === 'comment'
150
                ) {
151
                    $analysis[$lineNb][1] .= ' ' . $analysis[$lineNb + 1][1];
152
                    $analysis[$lineNb + 1][0] = 'erase';
153
154
                    break;
155
                } elseif ($line[0] === 'comment'
156
                    && isset($analysis[$lineNb + 1][0])
157
                    && $analysis[$lineNb + 1][0] === 'property'
158
                ) {
159
                    // $analysis[$lineNb + 1][3] = $line[1];
160
                    $analysis[$lineNb][0] = 'erase';
161
                } elseif ($line[0] === 'comment'
162
                    && isset($analysis[$lineNb + 1][0])
163
                    && $analysis[$lineNb + 1][0] === 'emptyline'
164
                ) {
165
                    // $analysis[$lineNb + 1][3] = $line[1];
166
                    $analysis[$lineNb][0] = 'erase';
167
                }
168
            }
169
170
            $counter = Utils::getNumberLinesMatching('comment', $analysis);
171
            $analysis = $this->deleteFields('erase', $analysis);
172
        }
173
174
        // Count emptylines
175
        $counter = Utils::getNumberLinesMatching('emptyline', $analysis);
176
177
        while ($counter > 0) {
178
            foreach ($analysis as $lineNb => $line) {
179
                if ($line[0] === 'emptyline') {
180
                    $analysis[$lineNb][0] = 'erase';
181
                }
182
            }
183
184
            $counter = Utils::getNumberLinesMatching('emptyline', $analysis);
185
            $analysis = $this->deleteFields('erase', $analysis);
186
        }
187
188
        // Third pass, we merge multiline strings
189
190
        // We remove the backslashes at end of strings if they exist
191
        $analysis = Utils::stripBackslashes($analysis);
192
193
        // Count # of multilines
194
        $counter = Utils::getNumberLinesMatching('multiline', $analysis);
0 ignored issues
show
Bug introduced by
It seems like $analysis defined by \Exen\Konfig\Utils::stripBackslashes($analysis) on line 191 can also be of type null; however, Exen\Konfig\Utils::getNumberLinesMatching() does only seem to accept array, 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...
195
196
        while ($counter > 0) {
197
            foreach ($analysis as $lineNb => $line) {
0 ignored issues
show
Bug introduced by
The expression $analysis of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
198
                if ($line[0] === 'multiline'
199
                    && isset($analysis[$lineNb - 1][0])
200
                    && $analysis[$lineNb - 1][0] === 'property'
201
                ) {
202
                    $analysis[$lineNb - 1][2] .= ' ' . trim($line[2]);
203
                    $analysis[$lineNb][0] = 'erase';
204
205
                    break;
206
                } elseif ($line[0] === 'multiline'
207
                    && isset($analysis[$lineNb - 1][0])
208
                    && $analysis[$lineNb - 1][0] === 'emptyline'
209
                ) {
210
                    // $analysis[$lineNb - 1][2] .= ' ' . trim($line[2]);
211
                    $analysis[$lineNb][0] = 'erase';
212
                }
213
            }
214
215
            $counter = Utils::getNumberLinesMatching('multiline', $analysis);
0 ignored issues
show
Bug introduced by
It seems like $analysis defined by \Exen\Konfig\Utils::stripBackslashes($analysis) on line 191 can also be of type null; however, Exen\Konfig\Utils::getNumberLinesMatching() does only seem to accept array, 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...
216
            $analysis = $this->deleteFields('erase', $analysis);
217
        }
218
219
        // Step 4, we clean up strings from escaped characters in properties
220
        $analysis = $this->unescapeProperties($analysis);
221
222
        // Step 5, we only have properties now, remove redondant field 0
223
        foreach ($analysis as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $analysis of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
224
            if (preg_match('/^[1-9][0-9]*$/', $value[2])) {
225
                $value[2] = intval($value[2]);
226
            }
227
228
            array_splice($analysis[$key], 0, 1);
229
        }
230
231
        return $analysis;
232
    }
233
234
    /**
235
     * {@inheritdoc}
236
     *
237
     * @param array|null $analysis Configuration items
238
     *
239
     * @return array The configuration items
240
     *
241
     * @since              0.2.4
242
     * @codeCoverageIgnore
243
     */
244
    private function unescapeProperties($analysis)
245
    {
246
        foreach ($analysis as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $analysis of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
247
            $analysis[$key][2] = str_replace('\=', '=', $value[2]);
248
        }
249
250
        return $analysis;
251
    }
252
253
    /**
254
     * {@inheritdoc}
255
     *
256
     * @param string     $field    Field name
257
     * @param array|null $analysis Configuration items
258
     *
259
     * @return array Configuration items after deletion
260
     *
261
     * @since              0.2.4
262
     * @codeCoverageIgnore
263
     */
264
    private function deleteFields($field, $analysis)
265
    {
266
        foreach ($analysis as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $analysis of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
267
            if ($value[0] === $field) {
268
                unset($analysis[$key]);
269
            }
270
        }
271
272
        return array_values($analysis);
273
    }
274
275
    /**
276
     * {@inheritdoc}
277
     *
278
     * @param string|bool|null $file File path
279
     *
280
     * @return array Configuration items
281
     *
282
     * @since              0.2.4
283
     * @codeCoverageIgnore
284
     */
285
    public function getProperties($file = null)
286
    {
287
        if ($file && !is_null($file)) {
288
            $this->loadFile($file);
289
        }
290
291
        $source = $this->parseProperties();
292
        $data = [];
293
294
        foreach ($source as $value) {
0 ignored issues
show
Bug introduced by
The expression $source of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
295
            Arr::set($data, $value[0], $value[1]);
296
        }
297
298
        unset($this->parsedFile);
299
300
        return $data;
301
    }
302
303
    /**
304
     * Loads in the given file and parses it.
305
     *
306
     * @param string|bool|null $file File to load
307
     *
308
     * @return array The parsed file data
309
     *
310
     * @since              0.2.4
311
     * @codeCoverageIgnore
312
     */
313
    protected function loadFile($file = null)
314
    {
315
        $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...
316
317
        $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...
318
319
        if ($this->file && !is_null($file)) {
320
            $this->parsedFile = Utils::fileContentToArray($contents);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Exen\Konfig\Utils::fileContentToArray($contents) of type array is incompatible with the declared type string of property $parsedFile.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
321
        }
322
    }
323
324
    /**
325
     * Returns the formatted configuration file contents.
326
     *
327
     * @param array $contents configuration array
328
     *
329
     * @return string formatted configuration file contents
330
     *
331
     * @since              0.2.4
332
     * @codeCoverageIgnore
333
     */
334
    protected function exportFormat($contents = null)
335
    {
336
        throw new Exception(
337
            'Saving configuration to `Properties` is not supported at this time'
338
        );
339
    }
340
341
    /**
342
     * __toString.
343
     *
344
     * @return             string
345
     * @since              0.1.2
346
     * @codeCoverageIgnore
347
     */
348
    public function __toString()
349
    {
350
        return 'Exen\Konfig\FileParser\Properties' . PHP_EOL;
351
    }
352
}
353
354
// END OF ./src/FileParser/Properties.php FILE
355