Completed
Push — master ( fe0d66...6612d0 )
by Daniel
04:01
created

CommonBasic::setArrayToArrayKbr()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 5
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
     * 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
    /**
64
     * Remove files older than given rule
65
     * (both Access time and Modified time will be checked
66
     * and only if both matches removal will take place)
67
     *
68
     * @param array $inputArray
69
     * @return string
70
     */
71
    protected function removeFilesOlderThanGivenRule($inputArray)
72
    {
73
        $proceedWithDeletion = false;
74
        if (is_array($inputArray)) {
75
            if (!isset($inputArray['path'])) {
76
                return '`path` has not been provided';
77
            } elseif (!isset($inputArray['dateRule'])) {
78
                return '`dateRule` has not been provided';
79
            }
80
            $proceedWithDeletion = true;
81
        }
82
        if ($proceedWithDeletion) {
83
            $finder   = new \Symfony\Component\Finder\Finder();
84
            $iterator = $finder
85
                    ->files()
86
                    ->ignoreUnreadableDirs(true)
87
                    ->followLinks()
88
                    ->in($inputArray['path']);
89
            $aFiles   = null;
90
            foreach ($iterator as $file) {
91
                if ($file->getATime() < strtotime($inputArray['dateRule'])) {
92
                    $aFiles[] = $file->getRealPath();
93
                }
94
            }
95
            if (is_null($aFiles)) {
96
                return null;
97
            } else {
98
                $filesystem = new \Symfony\Component\Filesystem\Filesystem();
99
                $filesystem->remove($aFiles);
100
                return $this->setArrayToJson($aFiles);
0 ignored issues
show
Bug introduced by
It seems like setArrayToJson() 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...
101
            }
102
        }
103
    }
104
105
    /**
106
     * Replace space with break line for each key element
107
     *
108
     * @param array $aElements
109
     * @return array
110
     */
111
    protected function setArrayToArrayKbr(array $aElements)
112
    {
113
        $aReturn = [];
114
        foreach ($aElements as $key => $value) {
115
            $aReturn[str_replace(' ', '<br/>', $key)] = $value;
116
        }
117
        return $aReturn;
118
    }
119
120
    /**
121
     * Converts a single-child array into an parent-child one
122
     *
123
     * @param type $inArray
124
     * @return type
125
     */
126
    protected function setArrayValuesAsKey(array $inArray)
127
    {
128
        $outArray = array_combine($inArray, $inArray);
129
        ksort($outArray);
130
        return $outArray;
131
    }
132
133
    /**
134
     * Provides a list of all known JSON errors and their description
135
     *
136
     * @return type
137
     */
138
    protected function setJsonErrorInPlainEnglish()
139
    {
140
        $knownErrors  = [
141
            JSON_ERROR_NONE           => null,
142
            JSON_ERROR_DEPTH          => 'Maximum stack depth exceeded',
143
            JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch',
144
            JSON_ERROR_CTRL_CHAR      => 'Unexpected control character found',
145
            JSON_ERROR_SYNTAX         => 'Syntax error, malformed JSON',
146
            JSON_ERROR_UTF8           => 'Malformed UTF-8 characters, possibly incorrectly encoded',
147
        ];
148
        $currentError = json_last_error();
149
        $sReturn      = null;
150
        if (in_array($currentError, $knownErrors)) {
151
            $sReturn = $knownErrors[$currentError];
152
        }
153
        return $sReturn;
154
    }
155
}
156