Completed
Push — master ( 49c86d...c6f12e )
by Daniel
01:20
created

decisionPackageOrPackageDev()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 7
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\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 decisionPackageOrPackageDev($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
        $pkgType  = $this->decisionPackageOrPackageDev($inParametersArray);
158
        foreach ($packages[$pkgType] as $key => $value) {
159
            $keyToUse = $value['name'];
160
            if (array_key_exists('Not Grouped By Name', $inParametersArray)) {
161
                $keyToUse = $key;
162
            }
163
            $alnfo[$keyToUse] = $this->mergeMultipleArrays($value, $inParametersArray);
164
            ksort($alnfo[$keyToUse]);
165
        }
166
        ksort($alnfo);
167
        return $alnfo;
168
    }
169
170
    private function getPkgAging($timePkg) {
171
        $dateTimeToday = new \DateTime(date('Y-m-d', strtotime('today')));
172
        $dateTime      = new \DateTime(date('Y-m-d', strtotime($timePkg)));
173
        $interval      = $dateTimeToday->diff($dateTime);
174
        return $interval->format('%a days ago');
175
    }
176
177
    private function getPkgBasicInfo($value, $defaultNA) {
178
        return [
179
            'License'      => (isset($value['license']) ? $this->getPkgLcns($value['license']) : $defaultNA),
180
            'Package Name' => $value['name'],
181
            'PHP required' => (isset($value['require']['php']) ? $value['require']['php'] : $defaultNA),
182
            'Product'      => explode('/', $value['name'])[1],
183
            'Vendor'       => explode('/', $value['name'])[0],
184
        ];
185
    }
186
187
    private function getPkgFileInListOfPackageArrayOut($fileToRead) {
188
        $handle       = fopen($fileToRead, 'r');
189
        $fileContents = fread($handle, filesize($fileToRead));
190
        fclose($handle);
191
        return json_decode($fileContents, true);
192
    }
193
194
    private function getPkgLcns($license) {
195
        $lcns = $license;
196
        if (is_array($license)) {
197
            $lcns = implode(', ', $license);
198
        }
199
        return $lcns;
200
    }
201
202
    private function getPkgOptAtributeAll($value, $defaultNA) {
203
        $attr    = ['description', 'homepage', 'type', 'url', 'version'];
204
        $aReturn = [];
205
        foreach ($attr as $valueA) {
206
            $aReturn[ucwords($valueA)] = $defaultNA;
207
            if (array_key_exists($valueA, $value)) {
208
                $aReturn[ucwords($valueA)] = $value[$valueA];
209
            }
210
        }
211
        return $aReturn;
212
    }
213
214
    private function getPkgTiming($value, $defaultNA) {
215
        if (isset($value['time'])) {
216
            return [
217
                'Aging'           => $this->getPkgAging($value['time']),
218
                'Time'            => date('l, d F Y H:i:s', strtotime($value['time'])),
219
                'Time as PHP no.' => strtotime($value['time']),
220
            ];
221
        }
222
        return ['Aging' => $defaultNA, 'Time' => $defaultNA, 'Time as PHP no.' => $defaultNA];
223
    }
224
225
    private function getPkgVerNo($version) {
226
        $vrs = $version;
227
        if (substr($version, 0, 1) == 'v') {
228
            $vrs = substr($version, 1, strlen($version) - 1);
229
        }
230
        if (strpos($vrs, '-') !== false) {
231
            $vrs = substr($vrs, 0, strpos($vrs, '-'));
232
        }
233
        return $vrs;
234
    }
235
236
    private function getPkgVersion($value, $defaultNA) {
237
        if (isset($value['version'])) {
238
            return [
239
                'Notification URL' => $value['notification-url'],
240
                'Version no.'      => $this->getPkgVerNo($value['version']),
241
            ];
242
        }
243
        return ['Notification URL' => $defaultNA, 'Version no.' => $defaultNA];
244
    }
245
246
    private function mergeMultipleArrays($value, $inParametersArray) {
247
        $atr   = $this->getPkgOptAtributeAll($value, '---');
248
        $basic = $this->getPkgBasicInfo($value, '---');
249
        $vrs   = $this->getPkgVersion($value, '---');
250
        $tmng  = $this->getPkgTiming($value, '---');
251
        if (array_key_exists('Skip Aging', $inParametersArray)) {
252
            unset($tmng['Aging']);
253
        }
254
        return array_merge($atr, $basic, $vrs, $tmng);
255
    }
256
257
}
258