Source::recruitment()   A
last analyzed

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 0
dl 0
loc 3
rs 10
1
<?php
2
3
namespace App\Models;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\SoftDeletes;
7
8
class Source extends Model
9
{
10
    use SoftDeletes;
11
12
    protected $connection = 'tenant';
13
14
    const SOURCE_KEY_MAXLENGTH = 8;
15
16
    protected $fillable = [
17
        'name',
18
        'recruitment_id',
19
    ];
20
21
    /**
22
     * Get the route key for the model.
23
     *
24
     * @return string
25
     */
26
    public function getRouteKeyName()
27
    {
28
        return 'key';
29
    }
30
31
    public function recruitment()
32
    {
33
        return $this->belongsTo(Recruitment::class);
34
    }
35
36
    protected function generateUniqueKey()
37
    {
38
        $this->key = $this->getUniqueKey();
39
    }
40
41
    protected static function getUniqueKey()
42
    {
43
        do {
44
            $key = strtoupper(substr(md5(uniqid()), 0, self::SOURCE_KEY_MAXLENGTH));
45
            $sources = Source::where('key', $key)->count();
46
        } while ($sources > 0);
47
48
        return $key;
49
    }
50
51
    public function save(array $options = [])
52
    {
53
        if (empty($this->key)) {
54
            $this->key = $this->getUniqueKey();
55
        }
56
        parent::save();
57
    }
58
}
59