Completed
Push — master ( a88dc9...5c5243 )
by Elf
05:22
created

OptimusHashidTrait::getKey()

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
nc 1
dl 0
loc 1
ccs 0
cts 0
cp 0
c 0
b 0
f 0
1
<?php
2
3
namespace ElfSundae\Laravel\Support\Services\Optimus;
4
5
trait OptimusHashidTrait
6
{
7
    /**
8
     * Get the value of the model's primary key.
9
     *
10
     * @return mixed
11
     */
12
    abstract public function getKey();
13
14
    /**
15
     * Get the table qualified key name.
16
     *
17
     * @return string
18
     */
19
    abstract public function getQualifiedKeyName();
20
21
    /**
22
     * Get the hashid for the given key.
23
     *
24
     * @param  mixed  $key
25
     * @return mixed
26
     */
27
    public function getHashidForKey($key)
28
    {
29
        $key = (int) $key;
30
31
        if ($key > 0) {
32
            return optimus_encode($key);
33
        }
34
    }
35
36
    /**
37
     * Get the key for the given hashid.
38
     *
39
     * @param  mixed  $hashid
40
     * @return mixed
41
     */
42
    public function getKeyForHashid($hashid)
43
    {
44
        $hashid = (int) $hashid;
45
46
        if ($hashid > 0) {
47
            return optimus_decode($hashid);
48
        }
49
    }
50
51
    /**
52
     * Get the `hashid` attribute.
53
     *
54
     * @return int
55
     */
56
    public function getHashidAttribute()
57
    {
58
        return $this->getHashidForKey($this->getKey());
59
    }
60
61
    /**
62
     * Scope a query to user of given hashid.
63
     *
64
     * @param  \Illuminate\Database\Eloquent\Builder  $query
65
     * @param  mixed  $hashid
66
     * @return \Illuminate\Database\Eloquent\Builder
67
     */
68
    public function scopeWhereHashid($query, $hashid)
69
    {
70
        return $query->where($this->getQualifiedKeyName(), $this->getKeyForHashid($hashid));
71
    }
72
}
73