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; |
|
|
|
|
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
|
|
|
} |