Completed
Push — master ( 1c947e...bdc0fb )
by Dmitry
02:52
created

PackageController::actionSearch()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 15
rs 9.4285
cc 3
eloc 9
nc 5
nop 1
1
<?php
2
3
namespace hiqdev\assetpackagist\controllers;
4
5
use yii\web\Controller;
6
use Exception;
7
use hiqdev\assetpackagist\commands\PackageUpdateCommand;
8
use hiqdev\assetpackagist\exceptions\UpdateRateLimitException;
9
use hiqdev\assetpackagist\models\AssetPackage;
10
use Yii;
11
use yii\filters\VerbFilter;
12
13
class PackageController extends Controller
14
{
15
    public function behaviors()
16
    {
17
        return [
18
            'access' => [
19
                'class' => VerbFilter::class,
20
                'actions' => [
21
                    'update' => ['post'],
22
                ],
23
            ],
24
        ];
25
    }
26
27
    public function actionUpdate()
28
    {
29
        session_write_close();
30
        $query = Yii::$app->request->post('query');
31
        $package = $this->getAssetPackage($query);
32
33
        try {
34
            if (!$package->canBeUpdated()) {
35
                throw new UpdateRateLimitException();
36
            }
37
38
            Yii::createObject(PackageUpdateCommand::class, [$package])->run();
39
        } catch (UpdateRateLimitException $exception) {
40
            Yii::$app->session->addFlash('rate-limited', true);
41
        } catch (\Composer\Downloader\TransportException $exception) {
42
            if (stripos($exception->getMessage(), 'not found')) {
43
                return $this->renderPartial('not-found', ['package' => $package]);
44
            }
45
46
            return $this->renderPartial('transport-error');
47
        }
48
49
        $package->load();
50
51
        return $this->renderPartial('details', ['package' => $package]);
52
    }
53
54
    public function actionSearch($query)
55
    {
56
        try {
57
            $package = $this->getAssetPackage($query);
58
            $params = ['package' => $package, 'query' => $query, 'forceUpdate' => false];
59
60
            if ($package->canAutoUpdate()) {
61
                $params['forceUpdate'] = true;
62
            }
63
        } catch (Exception $e) {
64
            return $this->render('wrong-name', compact('query'));
65
        }
66
67
        return $this->render('search', $params);
68
    }
69
70
    /**
71
     * @param string $query
72
     * @return AssetPackage
73
     */
74
    private static function getAssetPackage($query)
75
    {
76
        $filtredQuery = trim($query);
77
        $package = AssetPackage::fromFullName($filtredQuery);
78
        $package->load();
79
80
        return $package;
81
    }
82
}
83