/
DatabaseStorage.php
135 lines (121 loc) · 3.24 KB
/
DatabaseStorage.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<?php
namespace solarpatrol\tle;
use solarpatrol\tle\models\Tle;
use yii\di\Instance;
class DatabaseStorage extends Storage
{
/**
* @var string|array|\yii\db\Connection name, configuration or instance of database connection.
*/
public $db = 'db';
/**
* @inheritdoc
* @throws \yii\base\InvalidConfigException
*/
public function init()
{
parent::init();
$this->db = Instance::ensure($this->db);
}
/**
* @inheritdoc
*/
public function exists(&$tle)
{
$id = self::getNoradId($tle);
$timestamp = self::getEpochTimestamp($tle);
return Tle::find()
->where([
'norad_id' => $id,
'epoch_time' => gmdate('c', $timestamp)
])
->exists();
}
/**
* @inheritdoc
*/
public function add(&$tle)
{
if (!($tle instanceof Tle)) {
$tle = new Tle([
'norad_id' => self::getNoradId($tle),
'name' => self::getName($tle),
'epoch_time' => gmdate('c', self::getEpochTimestamp($tle)),
'line_1' => $tle[1],
'line_2' => $tle[2]
]);
}
return $tle->save(false);
}
/**
* @inheritdoc
*/
public function get($id, $startTime, $endTime)
{
$asArray = is_array($id);
$ids = $asArray ? $id : [$id];
$startTimestamp = self::timestamp($startTime);
$endTimestamp = self::timestamp($endTime);
/* @var $tles array */
$tles = Tle::find()
->select([
'id' => 'norad_id',
'name' => 'name',
'line1' => 'line_1',
'line2' => 'line_2',
])
->where(['norad_id' => $ids])
->andWhere(['>=', 'epoch_time', gmdate('c', $startTimestamp)])
->andWhere(['<=', 'epoch_time', gmdate('c', $endTimestamp)])
->orderBy(['epoch_time' => SORT_ASC])
->asArray()
->all();
$result = [];
foreach ($tles as $tle) {
$id = $tle['id'];
unset($tle['id']);
$tle['name'] = '0 ' . $tle['name'];
$tle = array_values($tle);
if ($asArray) {
if (!isset($result[$id])) {
$result[$id] = [];
}
$result[$id][] = $tle;
}
else {
$result[] = $tle;
}
}
return $result;
}
/**
* @inheritdoc
*/
public function remove(&$tle)
{
if (!($tle instanceof Tle)) {
$id = self::getNoradId($tle);
$timestamp = self::getEpochTimestamp($tle);
$tle = Tle::find()
->where([
'norad_id' => $id,
'epoch_time' => gmdate('c', $timestamp)
])
->one();
}
return $tle->delete() !== false ? true : false;
}
/**
* @inheritdoc
*/
public function getIds()
{
return Tle::find()
->select(['norad_id'])
->distinct()
->orderBy([
'norad_id' => SORT_ASC
])
->column();
}
}