Completed
Push — master ( 983ced...69f139 )
by Daniel
02:05
created

getPackageDetailsFromGivenComposerLockFileEnhanced()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 19
rs 9.2
cc 4
eloc 15
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\composer_packages_listing;
30
31
/**
32
 * usefull functions to get quick results
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait ComposerPackagesListing
37
{
38
39
    /**
40
     * Decision between Main or Development packages
41
     *
42
     * @param array $inParametersArray
43
     * @return string
44
     */
45
    private function decisionPackageOrPackageDevEnhanced($inParametersArray) {
46
        $sReturn = 'packages';
47
        if (array_key_exists('Dev', $inParametersArray)) {
48
            $sReturn = 'packages-dev';
49
        }
50
        return $sReturn;
51
    }
52
53
    /**
54
     * Exposes few Environment details
55
     *
56
     * @return array
57
     */
58
    protected function exposeEnvironmentDetails() {
59
        $knownValues = [
60
            'AMD64' => 'x64 (64 bit)',
61
            'i386'  => 'x86 (32 bit)',
62
            'i586'  => 'x86 (32 bit)',
63
        ];
64
        return [
65
            'Host Name'                     => php_uname('n'),
66
            'Machine Type'                  => php_uname('m'),
67
            'Operating System Architecture' => $knownValues[php_uname('m')],
68
            'Operating System Name'         => php_uname('s'),
69
            'Operating System Version'      => php_uname('r') . ' ' . php_uname('v'),
70
        ];
71
    }
72
73
    /**
74
     *
75
     * @return array
76
     */
77
    protected function exposePhpDetails($skipAging = false) {
78
        $aReturn = [
79
            'Aging'           => $this->getPkgAging($this->getFileModifiedTimestampOfFile(PHP_BINARY, 'Y-m-d')),
80
            'Architecture'    => (PHP_INT_SIZE === 4 ? 'x86 (32 bit)' : 'x64 (64 bit)'),
81
            'Description'     => 'PHP is a popular general-purpose scripting language'
82
            . ' that is especially suited to web development',
83
            'Homepage'        => 'https://secure.php.net/',
84
            'License'         => 'PHP License v3.01',
85
            'Package Name'    => 'ZendEngine/PHP',
86
            'Product'         => 'PHP',
87
            'Time'            => $this->getFileModifiedTimestampOfFile(PHP_BINARY, 'l, d F Y H:i:s'),
88
            'Time as PHP no.' => $this->getFileModifiedTimestampOfFile(PHP_BINARY, 'PHPtime'),
89
            'Type'            => 'scripting language',
90
            'Url'             => 'https://github.com/php/php-src',
91
            'Vendor'          => 'The PHP Group',
92
            'Version'         => PHP_VERSION,
93
            'Version no.'     => PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION,
94
        ];
95
        if ($skipAging) {
96
            unset($aReturn['Aging']);
97
        }
98
        return $aReturn;
99
    }
100
101
    /**
102
     * Returns Modified date and time of a given file
103
     *
104
     * @param string $fileName
105
     * @param string $format
106
     * @param boolean $resultInUtc
107
     * @return string
108
     */
109
    protected function getFileModifiedTimestampOfFile($fileName, $format = 'Y-m-d H:i:s', $resultInUtc = false) {
110
        if (!file_exists($fileName)) {
111
            return ['error' => $fileName . ' was not found'];
112
        }
113
        $info = new \SplFileInfo($fileName);
114
        if ($format === 'PHPtime') {
115
            return $info->getMTime();
116
        }
117
        $sReturn = date($format, $info->getMTime());
118
        if ($resultInUtc) {
119
            $sReturn = gmdate($format, $info->getMTime());
120
        }
121
        return $sReturn;
122
    }
123
124
    /**
125
     * Returns a complete list of packages and respective details from a composer.lock file
126
     * (kept for compatibility reason)
127
     *
128
     * @param string $fileIn
129
     * @param boolean $devInstead true for Development, false for Production
130
     * @param boolean $skipAging true for skipping, false for not
131
     * @return array
132
     */
133
    protected function getPackageDetailsFromGivenComposerLockFile($fileIn, $devInstead = false, $skipAging = false) {
134
        $inParametersArray = [];
135
        if ($devInstead) {
136
            $inParametersArray['Dev'] = true;
137
        }
138
        if ($skipAging) {
139
            $inParametersArray['Skip Aging'] = true;
140
        }
141
        return $this->getPackageDetailsFromGivenComposerLockFileEnhanced($fileIn, $inParametersArray);
142
    }
143
144
    /**
145
     * Returns a complete list of packages and respective details from a composer.lock file
146
     *
147
     * @param string $fileIn
148
     * @param array $inParametersArray
149
     * @return array
150
     */
151
    protected function getPackageDetailsFromGivenComposerLockFileEnhanced($fileIn, $inParametersArray = []) {
152
        if (!file_exists($fileIn)) {
153
            return ['error' => $fileIn . ' was not found'];
154
        }
155
        $alnfo    = [];
156
        $packages = $this->getPkgFileInListOfPackageArrayOut($fileIn);
157
        foreach ($packages[$this->decisionPackageOrPackageDevEnhanced($inParametersArray)] as $key => $value) {
158
            $atr      = $this->mergeMultipleArrays($value, $inParametersArray);
159
            $keyToUse = $value['name'];
160
            if (array_key_exists('Not Grouped By Name', $inParametersArray)) {
161
                $keyToUse    = $key;
162
                $atr['Name'] = $value['name'];
163
            }
164
            $alnfo[$keyToUse] = $atr;
165
            ksort($alnfo[$keyToUse]);
166
        }
167
        ksort($alnfo);
168
        return $alnfo;
169
    }
170
171
    private function mergeMultipleArrays($value, $inParametersArray) {
172
        $atr   = $this->getPkgOptAtributeAll($value, '---');
173
        $basic = $this->getPkgBasicInfo($value, '---');
174
        $vrs   = $this->getPkgVersion($value, '---');
175
        $tmng  = $this->getPkgTimingEnhanced($value, '---', $inParametersArray);
176
        return array_merge($atr, $basic, $vrs, $tmng);
177
    }
178
179
    private function getPkgAging($timePkg) {
180
        $dateTimeToday = new \DateTime(date('Y-m-d', strtotime('today')));
181
        $dateTime      = new \DateTime(date('Y-m-d', strtotime($timePkg)));
182
        $interval      = $dateTimeToday->diff($dateTime);
183
        return $interval->format('%a days ago');
184
    }
185
186
    private function getPkgBasicInfo($value, $defaultNA) {
187
        return [
188
            'License'      => (isset($value['license']) ? $this->getPkgLcns($value['license']) : $defaultNA),
189
            'Package Name' => $value['name'],
190
            'PHP required' => (isset($value['require']['php']) ? $value['require']['php'] : $defaultNA),
191
            'Product'      => explode('/', $value['name'])[1],
192
            'Vendor'       => explode('/', $value['name'])[0],
193
        ];
194
    }
195
196
    private function getPkgFileInListOfPackageArrayOut($fileToRead) {
197
        $handle       = fopen($fileToRead, 'r');
198
        $fileContents = fread($handle, filesize($fileToRead));
199
        fclose($handle);
200
        return json_decode($fileContents, true);
201
    }
202
203
    private function getPkgLcns($license) {
204
        $lcns = $license;
205
        if (is_array($license)) {
206
            $lcns = implode(', ', $license);
207
        }
208
        return $lcns;
209
    }
210
211
    private function getPkgOptAtributeAll($value, $defaultNA) {
212
        $attr    = ['description', 'homepage', 'type', 'url', 'version'];
213
        $aReturn = [];
214
        foreach ($attr as $valueA) {
215
            $aReturn[ucwords($valueA)] = $defaultNA;
216
            if (array_key_exists($valueA, $value)) {
217
                $aReturn[ucwords($valueA)] = $value[$valueA];
218
            }
219
        }
220
        return $aReturn;
221
    }
222
223
    private function getPkgTiming($value, $defaultNA) {
224
        if (isset($value['time'])) {
225
            return [
226
                'Aging'           => $this->getPkgAging($value['time']),
227
                'Time'            => date('l, d F Y H:i:s', strtotime($value['time'])),
228
                'Time as PHP no.' => strtotime($value['time']),
229
            ];
230
        }
231
        return ['Aging' => $defaultNA, 'Time' => $defaultNA, 'Time as PHP no.' => $defaultNA];
232
    }
233
234
    private function getPkgTimingEnhanced($value, $defaultNA, $inParametersArray) {
235
        $aReturn = $this->getPkgTiming($value, $defaultNA);
236
        if (array_key_exists('Skip Aging', $inParametersArray)) {
237
            unset($aReturn['Aging']);
238
        }
239
        return $aReturn;
240
    }
241
242
    private function getPkgVerNo($version) {
243
        $vrs = $version;
244
        if (substr($version, 0, 1) == 'v') {
245
            $vrs = substr($version, 1, strlen($version) - 1);
246
        }
247
        if (strpos($vrs, '-') !== false) {
248
            $vrs = substr($vrs, 0, strpos($vrs, '-'));
249
        }
250
        return $vrs;
251
    }
252
253
    private function getPkgVersion($value, $defaultNA) {
254
        if (isset($value['version'])) {
255
            return [
256
                'Notification URL' => $value['notification-url'],
257
                'Version no.'      => $this->getPkgVerNo($value['version']),
258
            ];
259
        }
260
        return ['Notification URL' => $defaultNA, 'Version no.' => $defaultNA];
261
    }
262
263
}
264