Completed
Push — master ( 13e33a...7c2796 )
by Vladimir
17s
created

ApiKey::getStatus()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
3
class ApiKey extends Model
4
{
5
    protected $name;
6
7
    protected $owner;
8
9
    protected $key;
10
11
    /**
12
     * The name of the database table used for queries
13
     */
14
    const TABLE = "api_keys";
15
16
    /**
17
     * {@inheritdoc}
18
     */
19
    protected function assignResult($key)
20
    {
21 1
        $this->name   = $key['name'];
22
        $this->owner  = Player::get($key['owner']);
23 1
        $this->key    = $key['key'];
24 1
        $this->status = $key['status'];
25 1
    }
26 1
27 1
    public static function createKey($name, $owner)
28
    {
29 1
        $key = self::create(array(
30
            'name'   => $name,
31 1
            'owner'  => $owner,
32 1
            'key'    => self::generateKey(),
33 1
            'status' => "active"
34 1
        ));
35 1
36
        return $key;
37
    }
38 1
39
    public static function getKeyByOwner($owner)
40
    {
41
        $key = self::fetchIdFrom($owner, "owner");
42
43
        if ($key == null) {
44
            return self::createKey("Automatically generated key", $owner);
45
        }
46
47
        return self::get($key);
48
    }
49
50
    public function getKey()
51
    {
52
        return $this->key;
53
    }
54
55
    public function getName()
56
    {
57
        return $this->name;
58
    }
59
60
    public function getOwner()
61
    {
62 1
        return $this->owner;
63
    }
64 1
65
    public static function getKeys($owner = -1)
66
    {
67
        if ($owner > 0) {
68
            $ids = self::fetchIdsFrom("owner", array($owner), false, "WHERE status = 'active'");
69
            return self::arrayIdToModel($ids);
70
        }
71
72
        $ids = self::fetchIdsFrom("status", array("active"));
73
        return self::arrayIdToModel($ids);
74
    }
75
76
    protected static function generateKey()
77
    {
78
        list($usec, $sec) = explode(' ', microtime());
79
        $seed = (float) $sec + ((float) $usec * 100000);
80
        srand($seed);
81
82
        $key = rand();
83 1
84
        return substr(sha1($key), 24);
85 1
    }
86
}
87