Completed
Pull Request — master (#142)
by Klochok
14:21
created

ResourceController   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 73
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 9

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 9
dl 0
loc 73
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A actionFetchResources() 0 18 2
A actionDrawChart() 0 23 2
A getResources() 0 27 2
1
<?php
2
3
namespace hipanel\controllers;
4
5
use DateTime;
6
use hipanel\base\CrudController;
7
use hipanel\helpers\ResourceHelper;
8
use hipanel\models\Resource;
9
use hipanel\models\ResourceSearch;
10
use hipanel\modules\server\widgets\ResourceConsumption;
11
use http\Exception\RuntimeException;
12
use Yii;
13
use yii\base\DynamicModel;
14
use yii\web\NotFoundHttpException;
15
use yii\web\Response;
16
17
class ResourceController extends CrudController
18
{
19
    public function actionFetchResources()
20
    {
21
        $request = Yii::$app->request;
22
        $response = Yii::$app->response;
23
        $response->format = Response::FORMAT_JSON;
24
        if ($request->isPost) {
25
            $resources = $this->getResources([
26
                'object_ids' => $request->post('object_ids'),
27
                'time_from' => $request->post('time_from'),
28
                'time_till' => $request->post('time_till'),
29
                'groupby' => 'server_traf_month',
30
            ]);
31
32
            return ResourceHelper::aggregateByObject($resources);
33
        }
34
35
        return [];
36
    }
37
38
    public function actionDrawChart()
39
    {
40
        $post = Yii::$app->request->post();
41
        $types = array_merge(['server_traf', 'server_traf95'], array_keys(ResourceConsumption::types()));
42
        if (!in_array($post['type'], $types, true)) {
43
            throw new NotFoundHttpException();
44
        }
45
46
        $searchModel = new ResourceSearch();
47
        $dataProvider = $searchModel->search([]);
48
        $dataProvider->pagination = false;
49
        $dataProvider->query->action('get-uses');
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface yii\db\QueryInterface as the method action() does only exist in the following implementations of said interface: hipanel\models\ResourceQuery, hiqdev\hiart\ActiveQuery, hiqdev\hiart\Query.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
50
        $dataProvider->query->andWhere($post);
51
        $models = $dataProvider->getModels();
52
53
        [$labels, $data] = ResourceHelper::groupResourcesForChart($models);
0 ignored issues
show
Bug introduced by
The variable $labels does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $data does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Documentation introduced by
$models is of type array|null, but the function expects a array<integer,object<hipanel\models\Resource>>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
54
55
        return $this->renderAjax('_chart', [
56
            'labels' => $labels,
57
            'data' => $data,
58
            'consumptionBase' => $post['type'],
59
        ]);
60
    }
61
62
    private function getResources(array $params): array
63
    {
64
        $options = DynamicModel::validateData([
65
            'object_ids' => $params['object_ids'],
66
            'time_from' => $params['time_from'] ?? (new DateTime())->modify('first day of last month')->format('Y-m-d'),
67
            'time_till' => $params['time_till'] ?? (new DateTime())->modify('last day of last month')->format('Y-m-d'),
68
            'groupby' => $params['groupby'],
69
        ], [
70
            [['object_ids', 'time_from', 'time_till', 'groupby'], 'required'],
71
            ['object_ids', 'string'],
72
            [['time_from', 'time_till'], 'datetime', 'format' => 'php:Y-m-d'],
73
            ['groupby', 'in', 'range' => ['server_traf_month', 'server_traf_week', 'server_traf_day']],
74
        ]);
75
        if ($options->hasErrors()) {
76
            throw new RuntimeException($options->getErrors()[0]);
77
        }
78
79
        return Resource::find()
80
            ->where([
81
                'object_id' => explode(',', $options->object_ids),
82
                'time_from' => $options->time_from,
83
                'time_till' => $options->time_till,
84
                'groupby' => $options->groupby,
85
            ])
86
            ->limit(-1)
87
            ->all();
88
    }
89
}
90