Completed
Push — master ( 4e28d8...f66e73 )
by Dmitry
08:49
created

BowerPackageController::actionFetchTop()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 20
ccs 0
cts 10
cp 0
rs 9.4285
cc 2
eloc 14
nc 2
nop 2
crap 6
1
<?php
2
3
namespace hiqdev\assetpackagist\console;
4
5
use Yii;
6
use yii\helpers\ArrayHelper;
7
use yii\helpers\Console;
8
use yii\helpers\Json;
9
10
class BowerPackageController extends \yii\console\Controller
11
{
12
    /**
13
     * Fetches TOP-$count components from Bower ans saves to `config/bower.list`
14
     *
15
     * @param int $count
16
     * @param bool $skipCache
17
     */
18
    public function actionFetchTop($count = 1000, $skipCache = false)
19
    {
20
        $result = [];
21
        $components = $this->getComponents($skipCache);
22
        ArrayHelper::multisort($components, 'stars', SORT_DESC, SORT_NUMERIC);
23
24
        foreach (array_slice($components, 0, $count) as $component) {
25
            $result[] = 'bower-asset/' . $component['name'];
26
            echo Console::renderColoredString("%R{$component['stars']}%N - %g{$component['name']}%N");
27
            Console::moveCursorTo(0);
28
            Console::clearLine();
29
        }
30
31
        $componentsListPath = Yii::getAlias('@hiqdev/assetpackagist/config/bower.list');
32
        file_put_contents($componentsListPath, implode("\n", $result));
33
34
        echo Console::renderColoredString("Fetched %YBower%N components list. Found %G" . count($components) . "%N components.\n");
35
        echo Console::renderColoredString("Only %bTOP-" . $count . "%N components were added to the packages list.\n");
36
        echo Console::renderColoredString("See %G" . $componentsListPath . "%N\n");
37
    }
38
39
    /**
40
     * Gets components array from bower API
41
     *
42
     * @param bool $skipCache whether to skip using local cache
43
     * @return array
44
     */
45
    private function getComponents($skipCache = false)
46
    {
47
        $url = 'http://bower-component-list.herokuapp.com';
48
        $componentsFilePath = Yii::getAlias('@runtime/bower-cache/components.list');
49
50
        if (!$skipCache && is_file($componentsFilePath) && (time() - filemtime($componentsFilePath) < 60*60*6)) { // 6 hours
51
            $raw = file_get_contents($componentsFilePath);
52
        } else {
53
            $result = (new \GuzzleHttp\Client())->request('GET', $url);
54
            $raw = $result->getBody();
55
            file_put_contents($componentsFilePath, $raw);
56
        }
57
58
        return Json::decode($raw);
59
    }
60
}
61