Completed
Push — master ( b1b67b...49c86d )
by Daniel
01:15
created

getPackageDetailsFromGivenComposerLockFileEnhanced()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

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