Passed
Pull Request — master (#129)
by
unknown
04:25
created

ProxyManager::invalidate()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
/**
3
 * Created for IG Monitoring.
4
 * User: jakim <[email protected]>
5
 * Date: 09.05.2018
6
 */
7
8
namespace app\components\http;
9
10
11
use app\models\Proxy;
12
use DateTime;
13
use Yii;
14
use yii\base\Component;
15
use yii\base\Exception;
16
use yii\base\InvalidConfigException;
17
18
class ProxyManager extends Component
19
{
20
    public $restTime = 1;
21
22
    public function reserve($model): Proxy
23
    {
24
        $uid = $this->generateUid();
25
26
        $condition = $this->prepareCondition($model);
27
28
        $sql = Yii::$app->db->createCommand()
29
            ->update('proxy', [
30
                'reservation_uid' => $uid,
31
                'updated_at' => (new DateTime())->format('Y-m-d H:i:s'),
32
            ], $condition)->rawSql;
33
34
        $n = Yii::$app->db->createCommand("{$sql} ORDER BY [[updated_at]] ASC LIMIT 1")
35
            ->execute();
36
37
        if (empty($n)) {
38
            throw new Exception('No proxy available.');
39
        }
40
41
        $proxy = Proxy::findOne(['reservation_uid' => $uid]);
42
43
        if (empty($proxy)) {
44
            throw new InvalidConfigException('Something is wrong with \'ProxyManager\'.');
45
        }
46
47
        return $proxy;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $proxy returns the type yii\db\ActiveRecord which includes types incompatible with the type-hinted return app\models\Proxy.
Loading history...
48
    }
49
50
    public function release(Proxy $proxy)
51
    {
52
        Proxy::updateAll(['reservation_uid' => null], 'reservation_uid=:reservation_uid', [':reservation_uid' => $proxy->reservation_uid]);
53
    }
54
55
    public function invalidate(Proxy $proxy)
56
    {
57
        Proxy::updateAll(['active' => false], 'id=:id', [':id' => $proxy->id]);
58
    }
59
60
    protected function generateUid()
61
    {
62
        return sprintf('%s_%s', Yii::$app->security->generateRandomString(64), time());
63
    }
64
65
    private function prepareCondition($model)
66
    {
67
        $andWhere = [
68
            'and',
69
            ['active' => 1],
70
            ['reservation_uid' => null],
71
            ['<=', 'updated_at', (new DateTime(sprintf('-%d seconds', (int) $this->restTime)))->format('Y-m-d H:i:s')],
72
        ];
73
74
        if ($model->proxy_id) {
75
            $andWhere[] = ['id' => $model->proxy_id];
76
        }
77
78
        return $andWhere;
79
    }
80
}