Completed
Push — master ( 59b1a5...9862f5 )
by Nikita
03:56
created

Composer::includeList()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 12
rs 9.2
cc 4
eloc 7
nc 4
nop 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: Nikita Kotenko
5
 * Date: 26.11.2014
6
 * Time: 14:12
7
 */
8
namespace samsonphp\composer;
9
10
11
/**
12
 * Provide creating sorting list of composer packages
13
 * @package samson
14
 */
15
class Composer
16
{
17
    /** @var string Path to current web-application */
18
    private $systemPath;
19
20
    /** @var string  composer lock file name */
21
    private $lockFileName = 'composer.lock';
22
23
    /** @var array List of available vendors */
24
    private $vendorsList = array();
25
26
    /** @var string $ignoreKey */
27
    private $ignoreKey;
28
29
    /** @var string $includeKey */
30
    private $includeKey;
31
32
    /** @var array List of ignored packages */
33
    private $ignorePackages = array();
34
35
    /** @var array  Packages list with require packages*/
36
    private $packagesList = array();
37
38
	private $packagesListExtra = array();
39
40
    private $projectRequireDev = array();
41
42
    /**
43
     *  Add available vendor
44
     * @param $vendor Available vendor
45
     * @return $this
46
     */
47
    public function vendor($vendor)
48
    {
49
        if (!in_array($vendor, $this->vendorsList)) {
50
            $this->vendorsList[] = $vendor.'/';
51
        }
52
        return $this;
53
    }
54
55
56
    /**
57
     * Set name of composer extra parameter to ignore package
58
     * @param $ignoreKey Name
59
     * @return $this
60
     */
61
    public function ignoreKey($ignoreKey)
62
    {
63
        $this->ignoreKey = $ignoreKey;
64
        return $this;
65
    }
66
67
    /**
68
     * Set name of composer extra parameter to include package
69
     * @param $includeKey Name
70
     * @return $this
71
     */
72
    public function includeKey($includeKey)
73
    {
74
        $this->includeKey = $includeKey;
75
        return $this;
76
    }
77
78
    /**
79
     *  Add ignored package
80
     * @param $vendor Ignored package
81
     * @return $this
82
     */
83
    public function ignorePackage($package)
84
    {
85
        if (!in_array($package, $this->ignorePackages)) {
86
            $this->ignorePackages[] = $package;
87
        }
88
        return $this;
89
    }
90
91
    /**
92
     * Create sorted packages list
93
     * @return array Packages list ('package name'=>'rating')
94
     */
95
    public function create(& $packages, $systemPath, $parameters = array())
96
    {
97
	    $class_vars = get_class_vars(get_class($this));
98
99
	    foreach ($class_vars as $name => $value) {
100
		    if (isset($parameters[$name])) {
101
			    $this->$name = $parameters[$name];
102
		    }
103
	    }
104
105
        // Create list of relevant packages with there require packages
106
        $this->packagesFill($this->readFile($systemPath));
107
108
        $resultList = $this->sort();
109
110
	    foreach ($resultList as $package => $rating) {
111
            $required = $this->getRequiredList($package);
112
		    $packages[$package] = $this->packagesListExtra[$package];
113
            $packages[$package]['required'] = $required;
114
            $packages[$package]['composerName'] =$package;
115
            $packages[$package]['projectRequireDev'] =
116
                in_array($package, $this->projectRequireDev)?true:false;
117
	    }
118
    }
119
120
    /**
121
     * Provide creating sorting list
122
     * @return array list of sorted packages
123
     */
124
    public function sort()
125
    {
126
        $list = array();
127
        foreach ($this->packagesList as $package => $requiredList) {
128
            if (!sizeof($list)||!isset($list[$package])) {
129
                $list[$package] = 1;
130
            }
131
            foreach ($requiredList as $requiredPackage) {
132
                if (isset($list[$requiredPackage])) {
133
                    $packagePos =  array_search($package, array_keys($list));
134
                    $requiredPackagePos = array_search($requiredPackage, array_keys($list));
135
                    if ($packagePos < $requiredPackagePos) {
136
                        unset($list[$requiredPackage]);
137
                        $list = $this->insertKeyBefore($list, $package, $requiredPackage);
138
                    }
139
                } else {
140
                    $list = $this->insertKeyBefore($list, $package, $requiredPackage);
141
                }
142
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
143
            }
144
        }
145
        //$this->checkSort($list);
146
147
        return $list;
148
    }
149
150
    /**
151
     *Check result of sorting
152
     * @param $list final list of packages
153
     *
154
     * @return bool result
155
     */
156
    public function checkSort($list)
157
    {
158
        $status = true;
159
        foreach ($this->packagesList as $package => $requiredList) {
160
            foreach ($requiredList as $requiredPackage) {
161
                if (isset($list[$requiredPackage])) {
162
                    $packagePos =  array_search($package, array_keys($list));
163
                    $requiredPackagePos = array_search($requiredPackage, array_keys($list));
164
                    if ($packagePos < $requiredPackagePos) {
165
                        trace('error pos - '.$packagePos.' < '.$requiredPackagePos);
166
                        $status = false;
167
                    }
168
                } else {
169
                    $status = false;
170
                    trace('error not isset!!!!! - '.$requiredPackage);
171
                }
172
            }
173
        }
174
        return $status;
175
    }
176
177
178
179
    /**
180
     * Create list of relevant packages
181
     * @param $packages Composer lock list of packages
182
     * @return array List of relevant packages
183
     */
184
    private function includeList($packages)
185
    {
186
        $includePackages = array();
187
        foreach ($packages as $package) {
188
            if (!$this->isIgnore($package)) {
189
                if ($this->isInclude($package)) {
190
                    $includePackages[] = $package['name'];
191
                }
192
            }
193
        }
194
        return $includePackages;
195
    }
196
197
    /**
198
     * Is package include
199
     * @param $package Composer package
200
     * @return bool - is package include
201
     */
202
    private function isInclude($package)
203
    {
204
        $include = true;
205
        if (sizeof($this->vendorsList)) {
206
            if (!isset($this->includeKey) || !isset($package['extra'][$this->includeKey])) {
207
                $packageName = $package['name'];
208
			    $vendorName = substr($packageName, 0, strpos($packageName,"/")+1);
209
                $include = in_array($vendorName, $this->vendorsList);
210
            }
211
        }
212
        return $include;
213
    }
214
215
    /**
216
     * Is package ignored
217
     * @param $package Composer package
218
     * @return bool - is package ignored
219
     */
220
    private function isIgnore($package)
221
    {
222
        $isIgnore = false;
223
        if (in_array($package['name'], $this->ignorePackages)) {
224
            $isIgnore = true;
225
        }
226
        if (isset($this->ignoreKey)&&(isset($package['extra'][$this->ignoreKey]))) {
227
            $isIgnore = true;
228
        }
229
        return $isIgnore;
230
    }
231
232
    /**
233
     * Fill list of relevant packages with there require packages
234
     * @param $packages Composer lock file object
235
     */
236
    private function packagesFill($packages)
237
    {
238
        // Get included packages list
239
        $includePackages = $this->includeList($packages);
240
241
        // Create list of relevant packages with there require packages
242
        foreach ($packages as $package) {
243
            $requirement = $package['name'];
244
            if (in_array($requirement, $includePackages)) {
245
                $this->packagesList[$requirement] = array();
246
	            $this->packagesListExtra[$requirement] = isset($package['extra'])?$package['extra']:array();
247
                if (isset($package['require'])) {
248
                    $this->packagesList[$requirement] = array_intersect(array_keys($package['require']), $includePackages);
249
                }
250
            }
251
        }
252
    }
253
254
    private function readFile($systemPath)
255
    {
256
        $packages = array();
257
        // Composer.lock is always in the project root folder
258
        $path = $systemPath.$this->lockFileName;
259
        // If we have composer configuration file
260
        if (file_exists($path)) {
261
            // Read file into object
262
            $composerObject = json_decode(file_get_contents($path), true);
263
264
            // Gather all possible packages
265
            $packages = array_merge(
266
                array(),
267
                isset($composerObject['packages']) ? $composerObject['packages'] : array(),
268
                isset($composerObject['packages-dev']) ? $composerObject['packages-dev'] : array()
269
            );
270
        }
271
272
        $jsonPath = $systemPath.'composer.json';
273
        if (file_exists($jsonPath)) {
274
            $jsonObject = json_decode(file_get_contents($jsonPath), true);
275
            $this->projectRequireDev = isset($jsonObject['require-dev'])?array_keys($jsonObject['require-dev']):array();
276
        }
277
278
        return $packages;
279
    }
280
281
    /**
282
     * Create list of of required packages
283
     * @param null $includeModule Dependent package
284
     * @param array $ignoreModules
285
     *
286
     * @return array required packages
287
     */
288
    private function getRequiredList($includeModule = null, $ignoreModules = array())
289
    {
290
        $list = isset($includeModule)?$this->packagesList[$includeModule]:$this->packagesList;
291
        $ignoreList = array();
292
        foreach ($ignoreModules as $module) {
293
            $ignoreList[] = $module;
294
            if (is_array($this->packagesList[$module])) {
295
                $ignoreList = array_merge($ignoreList, $this->packagesList[$module]);
296
            }
297
        }
298
299
        $result = array();
300
        foreach ($list as $k=>$v) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space before "=>"; 0 found
Loading history...
Coding Style introduced by
Expected 1 space after "=>"; 0 found
Loading history...
301
            $module = is_array($v)?$k:$v;
302 View Code Duplication
            if (!in_array($module, $ignoreList)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
303
                $result[] = $module;
304
                $moduleList = $this->getReqList($this->packagesList[$module]);
305
                $result = array_merge($result, $moduleList);
306
            }
307
        }
308
        return array_values(array_unique($result));
309
    }
310
311
    /**
312
     * Recursive function that get list of required packages
313
     * @param $list List of packages
314
     * @param array $result
315
     *
316
     * @return array required packages
317
     */
318
    private function getReqList($list, $result = array()) {
319
        $return = array();
320
        if (is_array($list)) {
321
            foreach ($list as $module) {
322 View Code Duplication
                if (!in_array($module, $result)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
323
                    $getList = $this->getReqList($this->packagesList[$module], $return);
324
                    $return[] = $module;
325
                    $return = array_merge($return, $getList);
326
                }
327
            }
328
        }
329
        return $return;
330
    }
331
332
	/**
333
	 * Clear object parameters
334
	 */
335
	public function clear()
336
	{
337
		$this->vendorsList = array();
338
		$this->ignoreKey = null;
339
		$this->includeKey = null;
340
		$this->ignorePackages = array();
341
		$this->packagesList = array();
342
	}
343
344
    /**
345
     * Insert a key after a specific key in an array.  If key doesn't exist, value is appended
346
     * to the end of the array.
347
     *
348
     * @param array $array
0 ignored issues
show
Bug introduced by
There is no parameter named $array. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
349
     * @param string $key
350
     * @param integer $newKey
351
     *
352
     * @return array
353
     */
354
    public function insertKeyAfter( array $list, $key, $newKey )
0 ignored issues
show
Coding Style introduced by
Expected 0 spaces between opening bracket and type hint "array"; 1 found
Loading history...
Coding Style introduced by
Expected 0 spaces between argument "$newKey" and closing bracket; 1 found
Loading history...
355
    {
356
        $keys = array_keys($list);
357
        $index = array_search( $key, $keys );
358
        $pos = false === $index ? count($list) : $index + 1;
359
        return array_merge(array_slice($list, 0, $pos), array($newKey=>1), array_slice($list, $pos));
360
    }
361
362
    /**
363
     * Insert a key before a specific key in an array.  If key doesn't exist, value is prepended
364
     * to the beginning of the array.
365
     *
366
     * @param array $array
0 ignored issues
show
Bug introduced by
There is no parameter named $array. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
367
     * @param string $key
368
     * @param integer $newKey
369
     *
370
     * @return array
371
     */
372
    public function insertKeyBefore(array $list, $key, $newKey)
373
    {
374
        $keys = array_keys($list);
375
        $pos = (int) array_search($key, $keys);
376
        return array_merge(array_slice($list, 0, $pos), array($newKey=>1), array_slice($list, $pos));
377
    }
378
379
}
380