Completed
Push — master ( 6091e1...47dbb9 )
by Daniel
03:05
created

CommonBasic::isJsonByDanielGP()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 6
nc 2
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
     * Moves files into another folder
41
     *
42
     * @param type $sourcePath
43
     * @param type $targetPath
44
     * @return type
45
     */
46
    protected function moveFilesIntoTargetFolder($sourcePath, $targetPath)
47
    {
48
        $filesystem = new \Symfony\Component\Filesystem\Filesystem();
49
        $filesystem->mirror($sourcePath, $targetPath);
50
        $finder     = new \Symfony\Component\Finder\Finder();
51
        $iterator   = $finder->files()->ignoreUnreadableDirs(true)->followLinks()->in($sourcePath);
52
        $sFiles     = [];
53
        foreach ($iterator as $file) {
54
            $relativePathFile = str_replace($sourcePath, '', $file->getRealPath());
55
            if (!file_exists($targetPath . $relativePathFile)) {
56
                $sFiles[$relativePathFile] = $targetPath . $relativePathFile;
57
            }
58
        }
59
        return $this->setArrayToJson($sFiles);
60
    }
61
62
    protected function removeFilesDecision($inputArray)
63
    {
64
        $proceedWithDeletion = false;
65
        if (is_array($inputArray)) {
66
            if (!isset($inputArray['path'])) {
67
                return '`path` has not been provided';
68
            } elseif (!isset($inputArray['dateRule'])) {
69
                return '`dateRule` has not been provided';
70
            }
71
            $proceedWithDeletion = true;
72
        }
73
        return $proceedWithDeletion;
74
    }
75
76
    /**
77
     * Remove files older than given rule
78
     * (both Access time and Modified time will be checked
79
     * and only if both matches removal will take place)
80
     *
81
     * @param array $inputArray
82
     * @return string
83
     */
84
    protected function removeFilesOlderThanGivenRule($inputArray)
85
    {
86
        $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...
87
        if (is_null($aFiles)) {
88
            return $aFiles;
89
        }
90
        $filesystem = new \Symfony\Component\Filesystem\Filesystem();
91
        $filesystem->remove($aFiles);
92
        return $this->setArrayToJson($aFiles);
93
    }
94
95
    protected function retrieveFilesOlderThanGivenRule($inputArray)
96
    {
97
        $proceedWithRetrieving = $this->removeFilesDecision($inputArray);
98
        if ($proceedWithRetrieving) {
99
            $finder   = new \Symfony\Component\Finder\Finder();
100
            $iterator = $finder->files()->ignoreUnreadableDirs(true)->followLinks()->in($inputArray['path']);
101
            $aFiles   = null;
102
            foreach ($iterator as $file) {
103
                if ($file->getATime() < strtotime($inputArray['dateRule'])) {
104
                    $aFiles[] = $file->getRealPath();
105
                }
106
            }
107
            return $aFiles;
108
        }
109
        return null;
110
    }
111
112
    /**
113
     * Replace space with break line for each key element
114
     *
115
     * @param array $aElements
116
     * @return array
117
     */
118
    protected function setArrayToArrayKbr(array $aElements)
119
    {
120
        $aReturn = [];
121
        foreach ($aElements as $key => $value) {
122
            $aReturn[str_replace(' ', '<br/>', $key)] = $value;
123
        }
124
        return $aReturn;
125
    }
126
127
    /**
128
     * Converts a single-child array into an parent-child one
129
     *
130
     * @param type $inArray
131
     * @return type
132
     */
133
    protected function setArrayValuesAsKey(array $inArray)
134
    {
135
        $outArray = array_combine($inArray, $inArray);
136
        ksort($outArray);
137
        return $outArray;
138
    }
139
140
    /**
141
     * Converts an array into JSON string
142
     *
143
     * @param array $inArray
144
     * @return string
145
     */
146
    protected function setArrayToJson(array $inArray)
147
    {
148
        $rtrn      = utf8_encode(json_encode($inArray, JSON_FORCE_OBJECT | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
149
        $jsonError = $this->setJsonErrorInPlainEnglish();
150
        if (is_null($jsonError)) {
151
            return $rtrn;
152
        } else {
153
            return $jsonError;
154
        }
155
    }
156
157
    /**
158
     * Provides a list of all known JSON errors and their description
159
     *
160
     * @return type
161
     */
162
    protected function setJsonErrorInPlainEnglish()
163
    {
164
        $knownErrors  = [
165
            JSON_ERROR_NONE           => null,
166
            JSON_ERROR_DEPTH          => 'Maximum stack depth exceeded',
167
            JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
168
            JSON_ERROR_CTRL_CHAR      => 'Unexpected control character found',
169
            JSON_ERROR_SYNTAX         => 'Syntax error, malformed JSON',
170
            JSON_ERROR_UTF8           => 'Malformed UTF-8 characters, possibly incorrectly encoded',
171
        ];
172
        $currentError = json_last_error();
173
        $sReturn      = null;
174
        if (in_array($currentError, $knownErrors)) {
175
            $sReturn = $knownErrors[$currentError];
176
        }
177
        return $sReturn;
178
    }
179
}
180