Completed
Push — master ( 777946...d26973 )
by Daniel
02:41
created

CommonBasic::retrieveFilesOlderThanGivenRule()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 16
rs 9.2
cc 4
eloc 11
nc 4
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 CommonBasic
37
{
38
39
    /**
40
     * Tests if given string has a valid Json format
41
     *
42
     * @param string $inputJson
43
     * @return boolean|string
44
     */
45
    protected function isJsonByDanielGP($inputJson)
46
    {
47
        if (is_string($inputJson)) {
48
            json_decode($inputJson);
49
            return (json_last_error() == JSON_ERROR_NONE);
50
        } else {
51
            return $this->lclMsgCmn('i18n_Error_GivenInputIsNotJson');
0 ignored issues
show
Bug introduced by
It seems like lclMsgCmn() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
52
        }
53
    }
54
55
    private function packIntoJson($aReturn, $keyToWorkWith)
56
    {
57
        if ($this->isJsonByDanielGP($aReturn[$keyToWorkWith])) {
58
            return '"' . $keyToWorkWith . '": ' . $aReturn[$keyToWorkWith];
59
        }
60
        return '"' . $keyToWorkWith . '": {' . $aReturn[$keyToWorkWith] . ' }';
61
    }
62
63
    protected function removeFilesDecision($inputArray)
64
    {
65
        $proceedWithDeletion = false;
66
        if (is_array($inputArray)) {
67
            if (!isset($inputArray['path'])) {
68
                return '`path` has not been provided';
69
            } elseif (!isset($inputArray['dateRule'])) {
70
                return '`dateRule` has not been provided';
71
            }
72
            $proceedWithDeletion = true;
73
        }
74
        return $proceedWithDeletion;
75
    }
76
77
    /**
78
     * Remove files older than given rule
79
     * (both Access time and Modified time will be checked
80
     * and only if both matches removal will take place)
81
     *
82
     * @param array $inputArray
83
     * @return string
84
     */
85
    protected function removeFilesOlderThanGivenRule($inputArray)
86
    {
87
        $aFiles = $this->retrieveFilesOlderThanGivenRule($inputArray);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $aFiles is correct as $this->retrieveFilesOlde...nGivenRule($inputArray) (which targets danielgp\common_lib\Comm...lesOlderThanGivenRule()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
88
        if (is_null($aFiles)) {
89
            return null;
90
        }
91
        $filesystem = new \Symfony\Component\Filesystem\Filesystem();
92
        $filesystem->remove($aFiles);
93
        $jsonResult = json_encode($aFiles, JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
94
        return utf8_encode($jsonResult);
95
    }
96
97
    protected function retrieveFilesOlderThanGivenRule($inputArray)
98
    {
99
        $proceedWithRetrieving = $this->removeFilesDecision($inputArray);
100
        if ($proceedWithRetrieving) {
101
            $finder   = new \Symfony\Component\Finder\Finder();
102
            $iterator = $finder->files()->ignoreUnreadableDirs(true)->followLinks()->in($inputArray['path']);
103
            $aFiles   = null;
104
            foreach ($iterator as $file) {
105
                if ($file->getATime() < strtotime($inputArray['dateRule'])) {
106
                    $aFiles[] = $file->getRealPath();
107
                }
108
            }
109
            return $aFiles;
110
        }
111
        return null;
112
    }
113
114
    /**
115
     * Replace space with break line for each key element
116
     *
117
     * @param array $aElements
118
     * @return array
119
     */
120
    protected function setArrayToArrayKbr(array $aElements)
121
    {
122
        $aReturn = [];
123
        foreach ($aElements as $key => $value) {
124
            $aReturn[str_replace(' ', '<br/>', $key)] = $value;
125
        }
126
        return $aReturn;
127
    }
128
129
    /**
130
     * Converts a single-child array into an parent-child one
131
     *
132
     * @param type $inArray
133
     * @return type
134
     */
135
    protected function setArrayValuesAsKey(array $inArray)
136
    {
137
        $outArray = array_combine($inArray, $inArray);
138
        ksort($outArray);
139
        return $outArray;
140
    }
141
142
    /**
143
     * Provides a list of all known JSON errors and their description
144
     *
145
     * @return type
146
     */
147
    protected function setJsonErrorInPlainEnglish()
148
    {
149
        $knownErrors  = [
150
            JSON_ERROR_NONE           => null,
151
            JSON_ERROR_DEPTH          => 'Maximum stack depth exceeded',
152
            JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
153
            JSON_ERROR_CTRL_CHAR      => 'Unexpected control character found',
154
            JSON_ERROR_SYNTAX         => 'Syntax error, malformed JSON',
155
            JSON_ERROR_UTF8           => 'Malformed UTF-8 characters, possibly incorrectly encoded',
156
        ];
157
        $currentError = json_last_error();
158
        $sReturn      = null;
159
        if (in_array($currentError, $knownErrors)) {
160
            $sReturn = $knownErrors[$currentError];
161
        }
162
        return $sReturn;
163
    }
164
}
165