Completed
Push — master ( 28285d...d07412 )
by Daniel
03:13
created

getContentFromUrlThroughCurlRawArray()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 28
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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