Completed
Push — master ( d9739a...b3b9ba )
by Daniel
02:37
created

CommonCode::setArrayToJson()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 1
Metric Value
c 6
b 0
f 1
dl 0
loc 13
rs 9.4286
cc 3
eloc 9
nc 3
nop 1
1
<?php
2
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2015 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\common_lib;
30
31
/**
32
 * usefull functions to get quick results
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait CommonCode
37
{
38
39
    use CommonLibLocale,
40
        DomComponentsByDanielGP,
41
        DomComponentsByDanielGPwithCDN,
42
        MySQLiByDanielGPqueries,
43
        MySQLiByDanielGP;
44
45
    protected function arrayDiffAssocRecursive($array1, $array2)
46
    {
47
        $difference = [];
48
        foreach ($array1 as $key => $value) {
49
            if (is_array($value)) {
50
                if (!isset($array2[$key]) || !is_array($array2[$key])) {
51
                    $difference[$key] = $value;
52
                } else {
53
                    $workingDiff = $this->arrayDiffAssocRecursive($value, $array2[$key]);
54
                    if (!empty($workingDiff)) {
55
                        $difference[$key] = $workingDiff;
56
                    }
57
                }
58
            } elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
59
                $difference[$key] = $value;
60
            }
61
        }
62
        return $difference;
63
    }
64
65
    /**
66
     * Returns an array with meaningfull content of permissions
67
     *
68
     * @param int $permissionNumber
69
     * @return array
70
     */
71
    protected function explainPermissions($permissionNumber)
72
    {
73
        if (($permissionNumber & 0xC000) == 0xC000) {
74
            $firstFlag = [
75
                'code' => 's',
76
                'name' => 'Socket',
77
            ];
78
        } elseif (($permissionNumber & 0xA000) == 0xA000) {
79
            $firstFlag = [
80
                'code' => 'l',
81
                'name' => 'Symbolic Link',
82
            ];
83
        } elseif (($permissionNumber & 0x8000) == 0x8000) {
84
            $firstFlag = [
85
                'code' => '-',
86
                'name' => 'Regular',
87
            ];
88
        } elseif (($permissionNumber & 0x6000) == 0x6000) {
89
            $firstFlag = [
90
                'code' => 'b',
91
                'name' => 'Block special',
92
            ];
93
        } elseif (($permissionNumber & 0x4000) == 0x4000) {
94
            $firstFlag = [
95
                'code' => 'd',
96
                'name' => 'Directory',
97
            ];
98
        } elseif (($permissionNumber & 0x2000) == 0x2000) {
99
            $firstFlag = [
100
                'code' => 'c',
101
                'name' => 'Character special',
102
            ];
103
        } elseif (($permissionNumber & 0x1000) == 0x1000) {
104
            $firstFlag = [
105
                'code' => 'p',
106
                'name' => 'FIFO pipe',
107
            ];
108
        } else {
109
            $firstFlag = [
110
                'code' => 'u',
111
                'name' => 'FIFO pipe',
112
            ];
113
        }
114
        $permissionsString    = substr(sprintf('%o', $permissionNumber), -4);
115
        $numericalPermissions = [
116
            0 => [
117
                'code' => '---',
118
                'name' => 'none',
119
            ],
120
            1 => [
121
                'code' => '--x',
122
                'name' => 'execute only',
123
            ],
124
            2 => [
125
                'code' => '-w-',
126
                'name' => 'write only',
127
            ],
128
            3 => [
129
                'code' => '-wx',
130
                'name' => 'write and execute',
131
            ],
132
            4 => [
133
                'code' => 'r--',
134
                'name' => 'read only',
135
            ],
136
            5 => [
137
                'code' => 'r-x',
138
                'name' => 'read and execute',
139
            ],
140
            6 => [
141
                'code' => 'rw-',
142
                'name' => 'read and write',
143
            ],
144
            7 => [
145
                'code' => 'rwx',
146
                'name' => 'read, write and execute',
147
            ],
148
        ];
149
        return [
150
            'Code'        => $permissionsString,
151
            'Overall'     => implode('', [
152
                $firstFlag['code'],
153
                $numericalPermissions[substr($permissionsString, 1, 1)]['code'],
154
                $numericalPermissions[substr($permissionsString, 2, 1)]['code'],
155
                $numericalPermissions[substr($permissionsString, 3, 1)]['code'],
156
            ]),
157
            'First'       => $firstFlag,
158
            'Owner'       => $numericalPermissions[substr($permissionsString, 1, 1)],
159
            'Group'       => $numericalPermissions[substr($permissionsString, 2, 1)],
160
            'World/Other' => $numericalPermissions[substr($permissionsString, 3, 1)],
161
        ];
162
    }
163
164
    /**
165
     * Reads the content of a remote file through CURL extension
166
     *
167
     * @param string $fullURL
168
     * @param array $features
169
     * @return blob
170
     */
171
    protected function getContentFromUrlThroughCurl($fullURL, $features = null)
172
    {
173
        if (!function_exists('curl_init')) {
174
            $aReturn['info']     = $this->lclMsgCmn('i18n_Error_ExtensionNotLoaded');
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aReturn was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aReturn = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
175
            $aReturn['response'] = '';
176
        }
177
        if (!filter_var($fullURL, FILTER_VALIDATE_URL)) {
178
            $aReturn['info']     = $this->lclMsgCmn('i18n_Error_GivenUrlIsNotValid');
0 ignored issues
show
Bug introduced by
The variable $aReturn 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...
179
            $aReturn['response'] = '';
180
        }
181
        $aReturn = [];
182
        $chanel  = curl_init();
183
        curl_setopt($chanel, CURLOPT_USERAGENT, $this->getUserAgentByCommonLib());
184
        if ((strpos($fullURL, 'https') !== false) || (isset($features['forceSSLverification']))) {
185
            curl_setopt($chanel, CURLOPT_SSL_VERIFYHOST, false);
186
            curl_setopt($chanel, CURLOPT_SSL_VERIFYPEER, false);
187
        }
188
        curl_setopt($chanel, CURLOPT_URL, $fullURL);
189
        curl_setopt($chanel, CURLOPT_HEADER, false);
190
        curl_setopt($chanel, CURLOPT_RETURNTRANSFER, true);
191
        curl_setopt($chanel, CURLOPT_FRESH_CONNECT, true); //avoid a cached response
192
        curl_setopt($chanel, CURLOPT_FAILONERROR, true);
193
        $rspJsonFromClient = curl_exec($chanel);
194
        if (curl_errno($chanel)) {
195
            $aReturn['info']     = $this->setArrayToJson([
196
                '#'           => curl_errno($chanel),
197
                'description' => curl_error($chanel)
198
            ]);
199
            $aReturn['response'] = '';
200
        } else {
201
            $aReturn['info']     = $this->setArrayToJson(curl_getinfo($chanel));
202
            $aReturn['response'] = $rspJsonFromClient;
203
        }
204
        curl_close($chanel);
205
        $sReturn = '';
0 ignored issues
show
Unused Code introduced by
$sReturn is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
206 View Code Duplication
        if ($this->isJsonByDanielGP($aReturn['info'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
207
            $sReturn = '"info": ' . $aReturn['info'];
208
        } else {
209
            $sReturn = '"info": {' . $aReturn['info'] . ' }';
210
        }
211
        $sReturn .= ', ';
212 View Code Duplication
        if ($this->isJsonByDanielGP($aReturn['response'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
213
            $sReturn .= '"response": ' . $aReturn['response'];
214
        } else {
215
            $sReturn .= '"response": { ' . $aReturn['response'] . ' }';
216
        }
217
        return '{ ' . $sReturn . ' }';
218
    }
219
220
    /**
221
     * Reads the content of a remote file through CURL extension
222
     *
223
     * @param string $fullURL
224
     * @param array $features
225
     * @return blob
226
     */
227
    protected function getContentFromUrlThroughCurlAsArrayIfJson($fullURL, $features = null)
228
    {
229
        $result = $this->setJsonToArray($this->getContentFromUrlThroughCurl($fullURL, $features));
230 View Code Duplication
        if (isset($result['info'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
231
            if (is_array($result['info'])) {
232
                ksort($result['info']);
233
            }
234
        }
235 View Code Duplication
        if (isset($result['response'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
236
            if (is_array($result['response'])) {
237
                ksort($result['response']);
238
            }
239
        }
240
        return $result;
241
    }
242
243
    protected function getFeedbackMySQLAffectedRecords()
244
    {
245
        if (is_null($this->mySQLconnection)) {
246
            $message = 'No MySQL';
247
        } else {
248
            $afRows  = $this->mySQLconnection->affected_rows;
249
            $message = sprintf($this->lclMsgCmnNumber('i18n_Record', 'i18n_Records', $afRows), $afRows);
250
        }
251
        return '<div>'
252
                . $message
253
                . '</div>';
254
    }
255
256
    /**
257
     * returns the details about Communicator (current) file
258
     *
259
     * @param string $fileGiven
260
     * @return array
261
     */
262
    protected function getFileDetails($fileGiven)
263
    {
264
        if (!file_exists($fileGiven)) {
265
            return [
266
                'error' => sprintf($this->lclMsgCmn('i18n_Error_GivenFileDoesNotExist'), $fileGiven)
267
            ];
268
        }
269
        $info    = new \SplFileInfo($fileGiven);
270
        $sReturn = [
271
            'File Extension'         => $info->getExtension(),
272
            'File Group'             => $info->getGroup(),
273
            'File Inode'             => $info->getInode(),
274
            'File Link Target'       => ($info->isLink() ? $info->getLinkTarget() : '-'),
275
            'File is Dir'            => $info->isDir(),
276
            'File is Executable'     => $info->isExecutable(),
277
            'File is File'           => $info->isFile(),
278
            'File is Link'           => $info->isLink(),
279
            'File is Readable'       => $info->isReadable(),
280
            'File is Writable'       => $info->isWritable(),
281
            'File Name'              => $info->getBasename('.' . $info->getExtension()),
282
            'File Name w. Extension' => $info->getFilename(),
283
            'File Owner'             => $info->getOwner(),
284
            'File Path'              => $info->getPath(),
285
            'File Permissions'       => array_merge([
286
                'Permissions' => $info->getPerms(),
287
                    ], $this->explainPermissions($info->getPerms())),
288
            'Name'                   => $info->getRealPath(),
289
            'Size'                   => $info->getSize(),
290
            'Sha1'                   => sha1_file($fileGiven),
291
            'Timestamp Accessed'     => [
292
                'PHP number' => $info->getATime(),
293
                'SQL format' => date('Y-m-d H:i:s', $info->getATime()),
294
            ],
295
            'Timestamp Changed'      => [
296
                'PHP number' => $info->getCTime(),
297
                'SQL format' => date('Y-m-d H:i:s', $info->getCTime()),
298
            ],
299
            'Timestamp Modified'     => [
300
                'PHP number' => $info->getMTime(),
301
                'SQL format' => date('Y-m-d H:i:s', $info->getMTime()),
302
            ],
303
            'Type'                   => $info->getType(),
304
        ];
305
        return $sReturn;
306
    }
307
308
    /**
309
     * returns a multi-dimensional array with list of file details within a given path
310
     * (by using Symfony/Finder package)
311
     *
312
     * @param  string $pathAnalised
313
     * @return array
314
     */
315
    protected function getListOfFiles($pathAnalised)
316
    {
317
        if (realpath($pathAnalised) === false) {
318
            $aFiles = [
319
                'error' => sprintf($this->lclMsgCmn('i18n_Error_GivenPathIsNotValid'), $pathAnalised)
320
            ];
321
        } elseif (!is_dir($pathAnalised)) {
322
            $aFiles = [
323
                'error' => $this->lclMsgCmn('i18n_Error_GivenPathIsNotFolder')
324
            ];
325
        } else {
326
            $finder   = new \Symfony\Component\Finder\Finder();
327
            $iterator = $finder
328
                    ->files()
329
                    ->sortByName()
330
                    ->in($pathAnalised);
331
            foreach ($iterator as $file) {
332
                $aFiles[$file->getRealPath()] = $this->getFileDetails($file);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aFiles was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aFiles = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
333
            }
334
        }
335
        return $aFiles;
0 ignored issues
show
Bug introduced by
The variable $aFiles 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...
336
    }
337
338
    /**
339
     * Returns server Timestamp into various formats
340
     *
341
     * @param string $returnType
342
     * @return string
343
     */
344
    protected function getTimestamp($returnType = 'string')
345
    {
346
        $crtTime = gettimeofday();
347
        switch ($returnType) {
348
            case 'array':
349
                $sReturn = [
350
                    'float'  => ($crtTime['sec'] + $crtTime['usec'] / pow(10, 6)),
351
                    'string' => implode('', [
352
                        '<span style="color:black!important;font-weight:bold;">[',
353
                        date('Y-m-d H:i:s.', $crtTime['sec']),
354
                        substr(round($crtTime['usec'], -3), 0, 3),
355
                        ']</span> '
356
                    ]),
357
                ];
358
                break;
359
            case 'float':
360
                $sReturn = ($crtTime['sec'] + $crtTime['usec'] / pow(10, 6));
361
                break;
362
            case 'string':
363
                $sReturn = implode('', [
364
                    '<span style="color:black!important;font-weight:bold;">[',
365
                    date('Y-m-d H:i:s.', $crtTime['sec']),
366
                    substr(round($crtTime['usec'], -3), 0, 3),
367
                    ']</span> '
368
                ]);
369
                break;
370
            default:
371
                $sReturn = sprintf($this->lclMsgCmn('i18n_Error_UnknownReturnType'), $returnType);
372
                break;
373
        }
374
        return $sReturn;
375
    }
376
377
    /**
378
     * Tests if given string has a valid Json format
379
     *
380
     * @param string $inputJson
381
     * @return boolean|string
382
     */
383
    protected function isJsonByDanielGP($inputJson)
384
    {
385
        if (is_string($inputJson)) {
386
            json_decode($inputJson);
387
            return (json_last_error() == JSON_ERROR_NONE);
388
        } else {
389
            return $this->lclMsgCmn('i18n_Error_GivenInputIsNotJson');
390
        }
391
    }
392
393
    /**
394
     * Moves files into another folder
395
     *
396
     * @param type $sourcePath
397
     * @param type $targetPath
398
     * @param type $overwrite
0 ignored issues
show
Bug introduced by
There is no parameter named $overwrite. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
399
     * @return type
400
     */
401
    protected function moveFilesIntoTargetFolder($sourcePath, $targetPath)
402
    {
403
        $filesystem = new \Symfony\Component\Filesystem\Filesystem();
404
        $filesystem->mirror($sourcePath, $targetPath);
405
        $finder     = new \Symfony\Component\Finder\Finder();
406
        $iterator   = $finder
407
                ->files()
408
                ->ignoreUnreadableDirs(true)
409
                ->followLinks()
410
                ->in($sourcePath);
411
        $sFiles     = [];
412
        foreach ($iterator as $file) {
413
            $relativePathFile = str_replace($sourcePath, '', $file->getRealPath());
414
            if (!file_exists($targetPath . $relativePathFile)) {
415
                $sFiles[$relativePathFile] = $targetPath . $relativePathFile;
416
            }
417
        }
418
        return $this->setArrayToJson($sFiles);
419
    }
420
421
    /**
422
     * Remove files older than given rule
423
     * (both Access time and Modified time will be checked
424
     * and only if both matches removal will take place)
425
     *
426
     * @param array $inputArray
427
     * @return string
428
     */
429
    protected function removeFilesOlderThanGivenRule($inputArray)
430
    {
431
        if (is_array($inputArray)) {
432
            if (!isset($inputArray['path'])) {
433
                $proceedWithDeletion = false;
434
                $error               = '`path` has not been provided';
435
            } elseif (!isset($inputArray['dateRule'])) {
436
                $proceedWithDeletion = false;
437
                $error               = '`dateRule` has not been provided';
438
            } else {
439
                $proceedWithDeletion = true;
440
            }
441
        } else {
442
            $proceedWithDeletion = false;
443
        }
444
        if ($proceedWithDeletion) {
445
            $finder   = new \Symfony\Component\Finder\Finder();
446
            $iterator = $finder
447
                    ->files()
448
                    ->ignoreUnreadableDirs(true)
449
                    ->followLinks()
450
                    ->in($inputArray['path']);
451
            $aFiles   = null;
452
            foreach ($iterator as $file) {
453
                if ($file->getATime() < strtotime($inputArray['dateRule'])) {
454
                    $aFiles[] = $file->getRealPath();
455
                }
456
            }
457
            if (is_null($aFiles)) {
458
                return null;
459
            } else {
460
                $filesystem = new \Symfony\Component\Filesystem\Filesystem();
461
                $filesystem->remove($aFiles);
462
                return $this->setArrayToJson($aFiles);
463
            }
464
        } else {
465
            return $error;
0 ignored issues
show
Bug introduced by
The variable $error 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...
466
        }
467
    }
468
469
    /**
470
     * Send an array of parameters like a form through a POST action
471
     *
472
     * @param string $urlToSendTo
473
     * @param array $params
474
     * @throws \Exception
475
     * @throws \UnexpectedValueException
476
     */
477
    protected function sendBackgroundEncodedFormElementsByPost($urlToSendTo, $params = [])
0 ignored issues
show
Coding Style introduced by
sendBackgroundEncodedFormElementsByPost uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
478
    {
479
        try {
480
            $postingUrl = filter_var($urlToSendTo, FILTER_VALIDATE_URL);
481
            if ($postingUrl === false) {
482
                throw new \Exception($exc);
483
            } else {
484
                if (is_array($params)) {
485
                    $postingString   = $this->setArrayToStringForUrl('&', $params);
486
                    $postingUrlParts = parse_url($postingUrl);
487
                    $postingPort     = (isset($postingUrlParts['port']) ? $postingUrlParts['port'] : 80);
488
                    $flPointer       = fsockopen($postingUrlParts['host'], $postingPort, $errNo, $errorMessage, 30);
489
                    if ($flPointer === false) {
490
                        throw new \UnexpectedValueException($this->lclMsgCmn('i18n_Error_FailedToConnect') . ': '
491
                        . $errNo . ' (' . $errorMessage . ')');
492
                    } else {
493
                        $out[] = 'POST ' . $postingUrlParts['path'] . ' ' . $_SERVER['SERVER_PROTOCOL'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$out was never initialized. Although not strictly required by PHP, it is generally a good practice to add $out = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
494
                        $out[] = 'Host: ' . $postingUrlParts['host'];
495
                        if (isset($_SERVER['HTTP_USER_AGENT'])) {
496
                            $out[] = 'User-Agent: ' . filter_var($_SERVER['HTTP_USER_AGENT'], FILTER_SANITIZE_STRING);
497
                        }
498
                        $out[] = 'Content-Type: application/x-www-form-urlencoded';
499
                        $out[] = 'Content-Length: ' . strlen($postingString);
500
                        $out[] = 'Connection: Close' . "\r\n";
501
                        $out[] = $postingString;
502
                        fwrite($flPointer, implode("\r\n", $out));
503
                        fclose($flPointer);
504
                    }
505
                } else {
506
                    throw new \UnexpectedValueException($this->lclMsgCmn('i18n_Error_GivenParameterIsNotAnArray'));
507
                }
508
            }
509
        } catch (\Exception $exc) {
510
            echo '<pre style="color:#f00">' . $exc->getTraceAsString() . '</pre>';
511
        }
512
    }
513
514
    /**
515
     * Converts an array into JSON string
516
     *
517
     * @param array $inArray
518
     * @return string
519
     */
520
    protected function setArrayToJson(array $inArray)
521
    {
522
        if (!is_array($inArray)) {
523
            return $this->lclMsgCmn('i18n_Error_GivenInputIsNotArray');
524
        }
525
        $rtrn      = utf8_encode(json_encode($inArray, JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
526
        $jsonError = $this->setJsonErrorInPlainEnglish();
527
        if (is_null($jsonError)) {
528
            return $rtrn;
529
        } else {
530
            return $jsonError;
531
        }
532
    }
533
534
    /**
535
     * Replace space with break line for each key element
536
     *
537
     * @param array $aElements
538
     * @return array
539
     */
540
    protected function setArrayToArrayKbr(array $aElements)
541
    {
542
        foreach ($aElements as $key => $value) {
543
            $aReturn[str_replace(' ', '<br/>', $key)] = $value;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$aReturn was never initialized. Although not strictly required by PHP, it is generally a good practice to add $aReturn = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
544
        }
545
        return $aReturn;
0 ignored issues
show
Bug introduced by
The variable $aReturn 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...
546
    }
547
548
    /**
549
     * Converts a single-child array into an parent-child one
550
     *
551
     * @param type $inArray
552
     * @return type
553
     */
554
    protected function setArrayValuesAsKey(array $inArray)
555
    {
556
        $outArray = array_combine($inArray, $inArray);
557
        ksort($outArray);
558
        return $outArray;
559
    }
560
561
    /**
562
     * Returns proper result from a mathematical division in order to avoid Zero division erorr or Infinite results
563
     *
564
     * @param float $fAbove
565
     * @param float $fBelow
566
     * @param mixed $mArguments
567
     * @return decimal
568
     */
569
    protected function setDividedResult($fAbove, $fBelow, $mArguments = 0)
570
    {
571
        // prevent infinite result AND division by 0
572
        if (($fAbove == 0) || ($fBelow == 0)) {
573
            $nReturn = 0;
574
        } else {
575
            if (is_array($mArguments)) {
576
                $nReturn = $this->setNumberFormat(($fAbove / $fBelow), [
577
                    'MinFractionDigits' => $mArguments[1],
578
                    'MaxFractionDigits' => $mArguments[1],
579
                ]);
580
            } else {
581
                $nReturn = $this->setNumberFormat(round(($fAbove / $fBelow), $mArguments));
582
            }
583
        }
584
        return $nReturn;
585
    }
586
587
    /**
588
     * Provides a list of all known JSON errors and their description
589
     *
590
     * @return type
591
     */
592
    private function setJsonErrorInPlainEnglish()
593
    {
594
        $knownErrors  = [
595
            JSON_ERROR_NONE           => null,
596
            JSON_ERROR_DEPTH          => 'Maximum stack depth exceeded',
597
            JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
598
            JSON_ERROR_CTRL_CHAR      => 'Unexpected control character found',
599
            JSON_ERROR_SYNTAX         => 'Syntax error, malformed JSON',
600
            JSON_ERROR_UTF8           => 'Malformed UTF-8 characters, possibly incorrectly encoded',
601
        ];
602
        $currentError = json_last_error();
603
        $sReturn      = null;
604
        if (in_array($currentError, $knownErrors)) {
605
            $sReturn = $knownErrors[$currentError];
606
        }
607
        return $sReturn;
608
    }
609
610
    /**
611
     * Converts a JSON string into an Array
612
     *
613
     * @param string $inputJson
614
     * @return array
615
     */
616
    protected function setJsonToArray($inputJson)
617
    {
618
        if (!$this->isJsonByDanielGP($inputJson)) {
619
            return [
620
                'error' => $this->lclMsgCmn('i18n_Error_GivenInputIsNotJson')
621
            ];
622
        }
623
        $sReturn   = (json_decode($inputJson, true));
624
        $jsonError = $this->setJsonErrorInPlainEnglish();
625
        if (is_null($jsonError)) {
626
            return $sReturn;
627
        } else {
628
            return [
629
                'error' => $jsonError
630
            ];
631
        }
632
    }
633
}
634